# Perl - determining the intersection of several numeric ranges

I would like to be able to load long list of positive integer ranges and create a new "summary" range list that is the union of the intersections of each pairs of ranges. And, I want to do this in Perl. For example:

Sample ranges: (1..30) (45..90) (15..34) (92..100) Intersection of ranges: (15..30)

The only way I could think of was using a bunch of nested if statements to determine the starting point of sample A, sample B, sample C, etc. and figure out the overlap this way, but it's not possible to do that with hundreds of sample, each containing numerous ranges.

Any suggestions are appreciated!

## Answers

The first thing you should do when you need to do some thing is take a look at CPAN to see what tools are available of if someone has solved your problem for you already.

Set::IntSpan and Set::IntRange are on the first page of results for "set" on CPAN.

What you want is the union of the intersection of each pair of ranges, so the algorithm is as follows:

- Create an empty result set.
- Create a set for each range.
- For each set in the list,
- For each later set in the list,
- Find the intersection of those two sets.
- Find the union of the result set and this intersection. This is the new result set.

- For each later set in the list,
- Enumerate the elements of the result set.