Icestope419
Icestope419

Reputation: 73

Kotlin: Run length encoding

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

        }


    }


}

Upvotes: 3

Views: 1099

Answers (4)

Priyanka
Priyanka

Reputation: 247

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
    }

Upvotes: 0

Vahe Gharibyan
Vahe Gharibyan

Reputation: 5683

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

Upvotes: 3

Andrei Tanana
Andrei Tanana

Reputation: 8432

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
        }
    }
}

Upvotes: 0

Icestope419
Icestope419

Reputation: 73

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

    }


}

}

Upvotes: 0

Related Questions