Sha256: 96719388696803f5fc9c3da432c95fe799c1919d27a9e7d1bbfeae29dbc17ac1

Contents?: true

Size: 870 Bytes

Versions: 337

Compression:

Stored size: 870 Bytes

Contents

object RunLengthEncoding {
  type Plain = String
  type Encoded = String

  def encode(str: Plain): Encoded = {
    def encodeGroup(xs: Seq[Char]): Seq[Char] =
      if (xs.length > 1) s"${xs.length}${xs.head}"
      else xs mkString

    splitByEquals(str) flatMap encodeGroup mkString
  }

  def decode(str: Encoded): Plain = {
    val nextChar: ((Int, Seq[Char]), Char) => (Int, Seq[Char]) = {
      case ((n, xs), x) =>
        if (x.isDigit) (n * 10 + x.asDigit, xs)
        else if (n == 0) (0, x +: xs)
        else (0, Seq.fill(n)(x) ++ xs)
    }

    val result = str.foldLeft((0, Seq.empty[Char]))(nextChar)
    result._2.reverse mkString
  }

  private def splitByEquals[T](xs: Seq[T]): Seq[Seq[T]] =
    xs match {
      case Seq() => Seq()
      case x +: xss =>
        val fs = xs takeWhile (_ == x)
        fs +: splitByEquals(xs drop fs.length)
    }
}

Version data entries

337 entries across 337 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/scala/exercises/run-length-encoding/example.scala
trackler-2.2.1.179 tracks/scala/exercises/run-length-encoding/example.scala
trackler-2.2.1.178 tracks/scala/exercises/run-length-encoding/example.scala
trackler-2.2.1.177 tracks/scala/exercises/run-length-encoding/example.scala
trackler-2.2.1.176 tracks/scala/exercises/run-length-encoding/example.scala
trackler-2.2.1.175 tracks/scala/exercises/run-length-encoding/example.scala
trackler-2.2.1.174 tracks/scala/exercises/run-length-encoding/example.scala
trackler-2.2.1.173 tracks/scala/exercises/run-length-encoding/example.scala
trackler-2.2.1.172 tracks/scala/exercises/run-length-encoding/example.scala
trackler-2.2.1.171 tracks/scala/exercises/run-length-encoding/example.scala
trackler-2.2.1.170 tracks/scala/exercises/run-length-encoding/example.scala
trackler-2.2.1.169 tracks/scala/exercises/run-length-encoding/example.scala
trackler-2.2.1.167 tracks/scala/exercises/run-length-encoding/example.scala
trackler-2.2.1.166 tracks/scala/exercises/run-length-encoding/example.scala
trackler-2.2.1.165 tracks/scala/exercises/run-length-encoding/example.scala
trackler-2.2.1.164 tracks/scala/exercises/run-length-encoding/example.scala
trackler-2.2.1.163 tracks/scala/exercises/run-length-encoding/example.scala
trackler-2.2.1.162 tracks/scala/exercises/run-length-encoding/example.scala
trackler-2.2.1.161 tracks/scala/exercises/run-length-encoding/example.scala
trackler-2.2.1.160 tracks/scala/exercises/run-length-encoding/example.scala