Created
June 24, 2014 16:48
-
-
Save DeepSky8/f0fc62ec67148b528f7d to your computer and use it in GitHub Desktop.
Run-length encoding of a list (direct solution). Implement the so-called run-length encoding data compression method directly. I.e. don't use other methods you've written (like P09's pack); do all the work directly. Example: scala> encodeDirect(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)) res0: List[(Int, Symbol)] = List((4,'a),…
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
| def encodeDirect[A](input: List[A]): List(Int, A) = input match { | |
| case Nil => Nil | |
| case h :: t => collapse(collate(input)) | |
| } | |
| def collate(input: List[A]): List[A] = input match { | |
| case Nil => Nil | |
| case h :: t => if(t.headOption.map(_==h).getThisOr(false)) h :: collate(t) else list(h) :: collate(t) | |
| } | |
| def collapse(input: List[List[A]]): List(Int, A) = input match{ | |
| case Nil => Nil | |
| case h :: t => List(h.length, h.head) :: collapse(t) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment