3

The program works, however, I still get a logical error: the final letter doesn't run through. For example, when I enter aaaabbbbccccdddd the output I get is a4b4c4 but there is no d4.

fun main () {

    val strUser = readLine()!!.toLowerCase()
    val iLength = strUser!!.length
    var iMatch : Int = 0
    var chrMatch : Char = strUser[0]

    for (i in 0..iLength) {

        if (strUser[i] == chrMatch) {

            iMatch += 1
        }else {
            print("$chrMatch$iMatch")
            chrMatch = strUser[i]
            iMatch = 1

        }


    }


}
halfer
  • 19,824
  • 17
  • 99
  • 186
  • When you iterate something, you need to go up to one less than its size or length, because the counting begins at zero. In this case, you could eliminate the `iLength` variable altogether and use `for (i in strUser.indices)`. Or more simply, you could use something like `for (chr in strUser)` and use `chr` in place of `strUser[i]`. – Tenfour04 May 21 '20 at 16:12
  • "this error thrown" - what error do you get? – halfer May 21 '20 at 20:51
  • its a loigcal error @halfer for example when i enter aaaabbbbccccdddd the output i get is a4b4c4 but there is no d4 – Icestope419 May 22 '20 at 14:18

4 Answers4

3

There are many solutions, but the best is RegExp

fun encode(input: String): String =
    input.replace(Regex("(.)\\1*")) {
        String.format("%d%s", it.value.length, it.groupValues[1])
    }

demo

Test result

println(encode("aaaabbbbccccdddd")) // 4a4b4c4d
Vahe Gharibyan
  • 5,277
  • 4
  • 36
  • 47
0

strUser contains chars by indexes from 0 to iLength - 1 so you have to write for (i in 0 until iLength) instead of for (i in 0..iLength)

But Tenfour04 is completely right, you can just iterate strUser without indexes:

fun main() {
    val strUser = readLine()!!.toLowerCase()
    var iMatch: Int = 0
    var chrMatch: Char = strUser[0]

    for (char in strUser) {
        if (char == chrMatch) {
            iMatch += 1
        } else {
            print("$chrMatch$iMatch")
            chrMatch = char
            iMatch = 1
        }
    }
}
Andrei Tanana
  • 7,932
  • 1
  • 27
  • 36
0

fun main () {

val strUser = readLine()!!.toLowerCase()
var iMatch : Int = 0
var chrMatch : Char = strUser[0]

for (char in strUser+1) {

    if (char == chrMatch) {

        iMatch += 1
    }else {
        print("$chrMatch$iMatch")
        chrMatch = char
        iMatch = 1

    }


}

}

0
fun runLengthEncoding(inputString: String): String {
        val n=inputString.length
        var i : Int =0
        var result : String =""
        while(i<n){
            var count =1
            while(i<n-1 && inputString[i] == inputString[i+1]){
                count ++
                i++
            }

            result=result.toString()+count.toString()+inputString[i].toString()
            i++
        }
        return result
    }
Priyanka
  • 247
  • 4
  • 19