Created
April 27, 2016 19:33
-
-
Save fredcy/0dd5d1d7296c37f1649e41752c61db8d to your computer and use it in GitHub Desktop.
Group overlapping intervals, in Elm
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
import Html exposing (text) | |
main = | |
text <| toString <| group data | |
type alias Interval = (Int, Int) | |
data = | |
[ (1, 2), (3, 5), (4, 10), (5, 8), (5, 12), (13, 15), (14, 20)] | |
group : List Interval -> List (List Interval) | |
group pairs = | |
List.foldl combine [] pairs | |
combine : Interval -> List (List Interval) -> List (List Interval) | |
combine interval groups = | |
case groups of | |
[] -> | |
[[interval]] | |
(first :: rest) -> | |
if overlapGroup interval first then | |
(interval :: first) :: rest | |
else | |
first :: combine interval rest | |
overlapGroup : Interval -> List Interval -> Bool | |
overlapGroup interval group = | |
List.any (overlapInterval interval) group | |
{- Do the two intervals overlap? This assumes that intervals are half-open | |
(include beginning value but not end value) and for each interval the begin | |
value is less than the end. -} | |
overlapInterval : Interval -> Interval -> Bool | |
overlapInterval (b1, e1) (b2, e2) = | |
if e1 <= b2 || e2 <= b1 then False else True | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment