Skip to content

Instantly share code, notes, and snippets.

@erlendaakre
Last active November 8, 2021 15:51
Show Gist options
  • Save erlendaakre/01cf39e70bbfd9d8107c85a8191cde00 to your computer and use it in GitHub Desktop.
Save erlendaakre/01cf39e70bbfd9d8107c85a8191cde00 to your computer and use it in GitHub Desktop.
import scala.annotation.tailrec
object VarLenEncoding extends App {
val testData = List(("", ""), ("XYZ", "XYZ"), ("AAABC", "A3BC"), ("XXXX", "X4"))
def encode(s: String): String = split(s, Nil).map(f => if (f.length == 1) f else s"${f.head}${f.length}").mkString
def decode(s: String): String = ???
@tailrec def split(s: String, acc: List[String]): List[String] = {
if (s.isEmpty) Nil
else {
val start: Char = s(0)
val bucket = s.takeWhile(p => p == start)
if (s.length - bucket.length == 0) acc ++ List(bucket)
else split(s.substring(bucket.length), acc ++ List(bucket))
}
}
testData.foreach { t =>
println(s"encoded: ${encode(t._1)}, expected: ${t._2}")
assert(encode(t._1) == t._2)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment