Created
February 29, 2012 23:07
-
-
Save Synesso/1945247 to your computer and use it in GitHub Desktop.
Ranges
This file contains 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 ranges(ints: Seq[Int]): Seq[(Int, Int)] = ranges(ints.sorted.distinct, Seq()) | |
def ranges(ints: Seq[Int], pairs: Seq[(Int, Int)]): Seq[(Int, Int)] = { | |
if (ints.isEmpty) pairs.reverse | |
else { | |
val (drop, take) = ints.zipWithIndex.partition{case (n,i) => (n == ints.head+i)} | |
ranges(take.unzip._1, (drop.unzip._1.head, drop.unzip._1.last) +: pairs) | |
} | |
} | |
assert(ranges(Seq()) == Seq()) // empty | |
assert(ranges(Seq(1)) == Seq((1,1))) // single value | |
assert(ranges(Seq(1,2,3)) == Seq((1,3))) // single range | |
assert(ranges(Seq(1,2,3,9)) == Seq((1,3),(9,9))) // 1 range, 1 value | |
assert(ranges(Seq(1,2,3,7,8,9)) == Seq((1,3),(7,9))) // two ranges | |
assert(ranges(Seq(5,7,3)) == Seq((3,3),(5,5),(7,7))) // distinct values unordered | |
assert(ranges(Seq(6,4,5)) == Seq((4,6))) // range unordered | |
assert(ranges(Seq(3,3,4,5,4,5)) == Seq((3,5))) // duplicates |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment