Skip to content

Instantly share code, notes, and snippets.

@dholbrook
Created February 2, 2012 01:06
Show Gist options
  • Save dholbrook/1720576 to your computer and use it in GitHub Desktop.
Save dholbrook/1720576 to your computer and use it in GitHub Desktop.
package scalaninetynine
/*
* S99 P10 http://aperiodic.net/phil/scala/s-99/
*
* Run-length encoding of a list.
*
* Use the result of problem P09 to implement the so-called run-length encoding
* data compression method. Consecutive duplicates of elements are encoded as
* tuples (N, E) where N is the number of duplicates of the element E.
*
* Example:
*
* scala> encode(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))
* res0: List[(Int, Symbol)] = List((4,'a), (1,'b), (2,'c), (2,'a), (1,'d), (4,'e))
*
* D. Holbrook 2012-01-31
*
*/
object S9910 extends App {
//Copy of P09
def pack[A](l: List[A]): List[List[A]] = {
l.foldLeft(List(List[A]())) {
case (acc, i) if acc.head == Nil || acc.head.head == i => (i :: acc.head) :: acc.tail
case (acc, i) => List(i) :: acc
}.reverse
}
def encode[A](l: List[A]): List[(Int, A)] = {
//for comprehension the same as map
//pack(l).map(sl => (sl.length,sl.head))
for (sl <- pack(l)) yield (sl.length, sl.head)
}
val r = encode(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))
assert(r == List((4, 'a), (1, 'b), (2, 'c), (2, 'a), (1, 'd), (4, 'e)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment