Skip to content

Instantly share code, notes, and snippets.

@dholbrook
Created February 2, 2012 01:08
Show Gist options
  • Save dholbrook/1720584 to your computer and use it in GitHub Desktop.
Save dholbrook/1720584 to your computer and use it in GitHub Desktop.
package scalaninetynine
/*
* S99 P11 http://aperiodic.net/phil/scala/s-99/
* Modified run-length encoding.
* Modify the result of problem P10 in such a way that if an element has no
* duplicates it is simply copied into the result list. Only elements with
* duplicates are transferred as (N, E) terms.
*
* Example:
*
* scala> encodeModified(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))
* res0: List[Any] = List((4,'a), 'b, (2,'c), (2,'a), 'd, (4,'e))
*
* D. Holbrook 2012-01-31
*/
object S9911 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 (sl <- pack(l)) yield (sl.length, sl.head)
}
def encodeModified[A](l: List[A]): List[Any] = {
for (ml <- encode(l)) yield (if (ml._1 == 1) ml._2 else ml)
}
val r = encodeModified(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))
assert(r == List((4, 'a), 'b, (2, 'c), (2, 'a), 'd, (4, 'e)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment