Skip to content

Instantly share code, notes, and snippets.

@baris
Created November 16, 2013 01:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baris/7494873 to your computer and use it in GitHub Desktop.
Save baris/7494873 to your computer and use it in GitHub Desktop.
scala compress, pack test functions
object TestProgram {
def compress1[T](lst: Seq[T]) = {
lst.foldRight(Seq[T]()) {
(n: T, compressed: Seq[T]) => if (compressed.headOption == Option(n)) compressed else n +: compressed
}
}
def compress2[T](lst: Seq[T]): Seq[T] = lst match {
case first :: second :: rest if (first == second) => compress2(second +: rest)
case first :: rest => first +: compress2(rest)
case Nil => Nil
}
def pack[T](lst: Seq[T]) = {
lst.foldRight(Seq[Seq[T]]()) {
(n: T, packed: Seq[Seq[T]]) => packed match {
case first :: rest if (first.headOption == Option(n)) => (n +: first) +: rest
case _ => Seq[T](n) +: packed
}
}
}
def main(args: Array[String]) = {
val arr = List(1,1,1,1,1,1,1,2,2,3,3,2,4,2,1)
println(arr)
println(compress1(arr))
println(compress2(arr))
println(pack(arr))
println(pack(arr).flatten == arr)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment