3
$\begingroup$

I think the following problem is a good exercise. In a List of Lists, merge lists which define neighbour intervals: for example,

list = {{1,2},{3.5,4.5},{4.5,10},{10,11},{13,14}}

should be "merged" as

{{1,2},{3.5,11},{13,14}}

It can be assumed that the elements are in the right order (i.e., not as in {{1,2},{3.5,4.5},{13,14},{4.5,10},{10,11}}. One way of doing it the following:

Select[Tally@Flatten@list, #[[2]] == 1 &][[All, 1]] // Partition[#, 2] &

It flattens list and keep the elements which appear only once, then partition. But I'm sure there are other possibly better solutions. Any ideas?

$\endgroup$
1
  • 6
    $\begingroup$ List@@Interval@@list $\endgroup$
    – LouisB
    Commented Nov 9, 2016 at 6:43

1 Answer 1

3
$\begingroup$

IntervalUnion:

IntervalUnion @@ (Interval /@ list) /. x_[y__] :> {y}

yields:

{{1, 2}, {3.5, 11}, {13, 14}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.