I have a string "abbbbccdddd" and the function should return "a1b4c2d4".
This is what I have written in Scala.
Iterative-version
def compress(str: String) = {
val chars = List(str).flatten.map(_.toString) ++ List(null)
var result: String = ""
var lookBack: String = chars.head
var occurance: Int = 0
chars.foreach { c =>
if (c != lookBack) {
result = result + lookBack.toString + occurance
occurance = 0
}
occurance = occurance + 1
lookBack = c
}
result
}
Recursive-version
def compress(str: String): String = {
def compressHandler(str: String, lookBack: String, occurance: Int, result: String): String = {
if(str.isEmpty) {
result
} else if(str.head.toString == lookBack) {
compressHandler(str.drop(1), str.head.toString, occurance + 1, result)
} else {
compressHandler(str, str.head.toString, 0, result + lookBack + occurance)
}
}
compressHandler(str + "0", str.head.toString, 0, "")
}
Scala — being a functional language should have much better solutions!
How to improve second (by somehow using map/reduce/fold) and how to do the first following concept of immutability (purely functional)?