Home > other >  How to get answer from this Spark Scala program for Input : s= 'aaabbbccaabb' Output : 3a3
How to get answer from this Spark Scala program for Input : s= 'aaabbbccaabb' Output : 3a3

Time:08-19

Scala program for Input :

s= 'aaabbbccaabb'

Output :

3a3b2c2a2b

find output by spark scala ?

CodePudding user response:

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("")

CodePudding user response:

          val data = "aaabbbccaabb"
          val fltlist = data.toList
          
          val ans = fltlist.map((_,1)).foldRight(Nil: List[(Char,Int)])((x,y) => y match {
          case Nil => List(x)
          case ((c,i)::rest) => if (c==x._1)(c,i 1):: rest else x::y
          })

          var i=0
          while (i< (ans.length))
          {
            print(ans(i)._2 "" ans(i)._1)
            i =1
          }
  • Related