chtefi
8/18/2016 - 8:21 PM

"aabbc" to "a2b2c" in Scala (sequential group by)

"aabbc" to "a2b2c" in Scala (sequential group by)

val a = "abcaaabbb"

// result will be: abca3b3

// functional way: foldLeft
println(a.tail.foldLeft(List((a.head, 1)))((acc: List[(Char, Int)], c: Char) =>
  if (acc.head._1 == c) (c, acc.head._2 + 1) :: acc.tail else (c, 1) :: acc
).reverse.map(x =>  x._1.toString + (if (x._2 > 1) x._2 else "")).mkString(""))

// recursive way
@tailrec
def compress(msg: List[Char], last: String = "", count: Int = 0, result: StringBuilder = new StringBuilder): String = {
  msg match {
    case Nil => result + last + (if(count > 0) count + 1 else "")
    case head :: tail =>
      if (last.length > 0 && head == last.head)
        compress(tail, head.toString, count + 1, result)
      else {
        result ++= last + (if (count > 0) count + 1 else "")
        compress(tail, head.toString, 0, result)
      }
  }
}
// Note: just think of that, but we could append the new char directly to the StringBuilder, and just add the number in the latter iterations if necessary.

println(compress(a.toList))