Skip to content

Instantly share code, notes, and snippets.

@bgreenlee
Last active December 15, 2015 18:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bgreenlee/5305273 to your computer and use it in GitHub Desktop.
Save bgreenlee/5305273 to your computer and use it in GitHub Desktop.
Coalesce a list of overlapping start/end tuples
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)
}
}
@kwarrick
Copy link

Thanks mate! I had the same intuition, but bumbled the execution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment