Created
February 10, 2012 10:18
-
-
Save Aankhen/1788524 to your computer and use it in GitHub Desktop.
Ensuring contiguity among pairs
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 ensureContiguity(xs: List[(Int, Int)], acc: List[(Int, Int)] = List.empty): List[(Int, Int)] = | |
(xs, acc) match { | |
case (Nil, l) => l | |
case (l, Nil) => ensureContiguity(l dropRight 1, List(l.last)) | |
case _ => { | |
val t = xs.last | |
val h = acc.head | |
if (t._2 == h._1) | |
ensureContiguity(xs dropRight 1, t +: acc) | |
else | |
ensureContiguity(xs dropRight 1, t +: (t._2, h._1) +: acc) | |
} | |
} | |
/* | |
scala> ensureContiguity(List((1, 2), (2, 3), (6, 9), (10, 11))) | |
res3: List[(Int, Int)] = List((1,2), (2,3), (3,6), (6,9), (9,10), (10,11)) | |
scala> ensureContiguity(List((4, 9), (40, 200))) | |
res4: List[(Int, Int)] = List((4,9), (9,40), (40,200)) | |
scala> ensureContiguity(List.empty) | |
res5: List[(Int, Int)] = List() | |
scala> ensureContiguity(List((1, 2), (2, 3))) | |
res6: List[(Int, Int)] = List((1,2), (2,3)) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment