[Solved] How to get answer from this Spark Scala program for Input : s= ‘aaabbbccaabb’ Output : 3a3b2c2a2b


You can foldLeft over the input string, with a state of List[(Char, Int)]. Note that if you use Map[Char, Int], all occurrences of each character would be added up, weather they’re beside each other or not.

s.foldLeft(List.empty[(Char, Int)]) {
  case (Nil, newChar) => (newChar, 1) :: Nil
  case (list@(headChar, headCount) :: tail, newChar) => 
    if (headChar == newChar) 
      (headChar, headCount + 1) :: tail
    else 
      (newChar, 1) :: list
}.map {
  case (char, count) => s"$count$char"
}
  .reverse // because we're prepending to the list, the reverse order of the iteration
  .mkString("")

solved How to get answer from this Spark Scala program for Input : s= ‘aaabbbccaabb’ Output : 3a3b2c2a2b