Last active
December 15, 2015 18:39
-
-
Save bgreenlee/5305273 to your computer and use it in GitHub Desktop.
Coalesce a list of overlapping start/end tuples
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
val ranges = List((2,3), (1,2), (5,11), (4,10), (3,3), (6,7), (15,16)) | |
ranges.sorted.foldLeft(List[(Int, Int)]()) { (acc, t) => | |
acc match { | |
case x :: xs if x._2 >= t._1 => (x._1, math.max(x._2, t._2)) :: xs | |
case x :: xs => t +: acc | |
case _ => List(t) | |
} | |
}.reverse | |
// List((1,3), (4,11), (15,16)) | |
// variation for Scala 2.10, which allows case init :+ last => | |
// not sure if that operation is optimized, though | |
ranges.sorted.foldLeft(List[(Int, Int)]()) { (acc, t) => | |
acc match { | |
case init :+ last if last._2 >= t._1 => init :+ (last._1, math.max(last._2, t._2)) | |
case init :+ last => acc :+ t | |
case _ => List(t) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks mate! I had the same intuition, but bumbled the execution.