Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a very large array like the following:


Now, imagine that every element in the array corresponds to an integer interval. I'd like to delete elements in the array that fall within a larger interval, and whenever there is an interval-interval overlap, I'd like to shrink the intersecting intervals to eliminate the overlap and then add the former section where the overlap occurred as a new element to a separate array (here I'm calling this overlapArray).

Perhaps this is best explained by example. Looking at the smaller case:


We notice that there is an overlap between the first three elements of the array, and that the element {8,9} falls entirely in this overlap section. So we this array becomes the following after our procedure:


overlapArray = {{8,10}};

Now for the full example, this:




overlapArray = {{8,10},{47,50}};

Is there an elegant way to do this with list operations in Mathematica v9?

share|improve this question
@Kuba Sorry, were you preparing a response? I thought it was too open-ended and that it was a bad question. I thought from this, and your previous answer, I could figure out how to do it. But if you have a response, or you think it was wrong for me to do this, I will undelete it! – Bob2Alice Apr 1 '14 at 9:49
@Kuba Whatever you'd like, my priority was just not to be a nuisance here, so I was acting accordingly. – Bob2Alice Apr 1 '14 at 9:51
@Kuba It's back! – Bob2Alice Apr 1 '14 at 10:00
up vote 4 down vote accepted

I like this one :P

list = {{1, 10}, {8, 9}, {9, 20}, {34, 40}, {41, 42}, {43, 50}, {47, 53}}

 Split[#, #2 - #1 == 1 &][[ All , {1, -1}]] &,
 DeleteCases[#, {_, 1}][[ All , 1]] &,
 Range @@@ # &
 {{8, 10}, {47, 50}}
share|improve this answer
This can be written in compact way but now it is more readable. – Kuba Apr 1 '14 at 9:52
Cool! That sure was fast. Is there a way to modify the original list to get: {{1,7},{11,20},{34,40},{41,42},{43,46},{51,53}? BTW, I can't upvote yet due to my low rep. – Bob2Alice Apr 1 '14 at 9:52
@Bob2Alice just change DeleteCases to Cases :) – Kuba Apr 1 '14 at 9:53
Ooooh nice nice. +1 – Bob2Alice Apr 1 '14 at 9:56
Slickly done. +1 – ciao Apr 1 '14 at 9:57

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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