Last active
August 29, 2015 13:57
-
-
Save rkrzewski/9374106 to your computer and use it in GitHub Desktop.
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[T](ts: Seq[T]): Seq[(Int, T)] = { | |
@tailrec | |
def go(ts: Seq[T], acc: Seq[(Int, T)]): Seq[(Int, T)] = ts match { | |
case Seq() => acc | |
case head +: tail => | |
val (same, different) = ts.span(_ == head) | |
go(different, acc :+ (same.length, head)) | |
} | |
go(ts, Seq()) | |
} | |
@tailrec | |
def nth[T](k: Int, ts: Seq[T]): T = (k, ts) match { | |
case (0, t +: ts) => t | |
case (k, t +: ts) if k > 0 => nth(k - 1, ts) | |
case _ => throw new NoSuchElementException | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment