Skip to main content
use pattern matching for map; added 8 characters in body
Source Link

Here's my take using foldLeft:

def compress(s: String) = {
    val a : List[(Char,Int)] = List()
    s.toCharArray.foldLeft(a)((acc, elem) => acc match {
        case Nil => (elem, 1) :: Nil
        case head(a, b) :: tail =>
            if (head._1a == elem) (elem, head._2b + 1) :: tail else (elem, 1) :: acc
    }).reverse
    .map{ case (ea, b) => e._1a.toString + e._2)b }
    .mkString("")
}

Note: I have assumed that order matters. That is, aabbbaa will reduce to a2b3a2

Here's my take using foldLeft:

def compress(s: String) = {
    val a : List[(Char,Int)] = List()
    s.toCharArray.foldLeft(a)((acc, elem) => acc match {
        case Nil => (elem, 1) :: Nil
        case head :: tail => if (head._1 == elem) (elem, head._2 + 1) :: tail else (elem,1) :: acc
    }).reverse
    .map(e => e._1.toString + e._2)
    .mkString("")
}

Note: I have assumed that order matters. That is, aabbbaa will reduce to a2b3a2

Here's my take using foldLeft:

def compress(s: String) = {
    val a : List[(Char,Int)] = List()
    s.toCharArray.foldLeft(a)((acc, elem) => acc match {
        case Nil => (elem, 1) :: Nil
        case (a, b) :: tail =>
            if (a == elem) (elem, b + 1) :: tail else (elem, 1) :: acc
    }).reverse
    .map{ case (a, b) => a.toString + b }
    .mkString("")
}

Note: I have assumed that order matters. That is, aabbbaa will reduce to a2b3a2

Source Link

Here's my take using foldLeft:

def compress(s: String) = {
    val a : List[(Char,Int)] = List()
    s.toCharArray.foldLeft(a)((acc, elem) => acc match {
        case Nil => (elem, 1) :: Nil
        case head :: tail => if (head._1 == elem) (elem, head._2 + 1) :: tail else (elem,1) :: acc
    }).reverse
    .map(e => e._1.toString + e._2)
    .mkString("")
}

Note: I have assumed that order matters. That is, aabbbaa will reduce to a2b3a2