Created
November 16, 2013 01:55
-
-
Save baris/7494873 to your computer and use it in GitHub Desktop.
scala compress, pack test functions
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
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