Skip to content

Instantly share code, notes, and snippets.

@ajozwik
Created January 22, 2014 17:37
Show Gist options
  • Save ajozwik/8563285 to your computer and use it in GitHub Desktop.
Save ajozwik/8563285 to your computer and use it in GitHub Desktop.
object S99_P10 {
def encode[T](ts: Seq[T]): Seq[(Int, T)] = {
val (_, _, l, last) = ts.foldRight[(Int, Option[T], Seq[(Int, T)], (Int, Option[T]))]((0, None, Nil, (0, None))) {
(el, q) =>
val (nr, option, acc, _) = q
option match {
case None => (1, Some(el), acc, (1, Some(el)))
case Some(x) => if (x == el) {
(nr + 1, Some(el), acc, (nr + 1, Some(el)))
} else {
(1, Some(el), (nr, x) +: acc, (nr + 1, Some(el)))
}
}
}
val (nr, opt) = last
opt match{
case None =>l
case Some(x) =>(nr, x) +: l
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment