Created
February 16, 2012 18:50
-
-
Save dholbrook/1846986 to your computer and use it in GitHub Desktop.
S99 P12
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* S99 P12 http://aperiodic.net/phil/scala/s-99/ | |
* | |
* Decode a run-length encoded list. | |
* | |
* Given a run-length code list generated as specified in problem P10, | |
* construct its uncompressed version. | |
* | |
* Example: | |
* | |
* scala> decode(List((4, 'a), (1, 'b), (2, 'c), (2, 'a), (1, 'd), (4, 'e))) | |
* res0: List[Symbol] = List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e) | |
*/ | |
object S9912 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 | |
} | |
//Copy of P10 | |
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) | |
} | |
//verbose version | |
def decode[A](l: List[(Int, A)]): List[A] = { | |
l.flatMap({ tpl: (Int, A) => | |
tpl match { | |
case (count, item) => List.make(count, item) | |
} | |
}) | |
} | |
//Exactly the same as decoded, but with collapsed match/case syntax | |
def decodeShorter[A](l: List[(Int, A)]): List[A] = { | |
l flatMap { case (count, item) => List.make(count, item) } | |
} | |
val r = decode(List((4, 'a), (1, 'b), (2, 'c), (2, 'a), (1, 'd), (4, 'e))) | |
println(r) | |
val r2 = decodeShorter(List((4, 'a), (1, 'b), (2, 'c), (2, 'a), (1, 'd), (4, 'e))) | |
assert(r == List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)) | |
assert(r2 == List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment