MathGroup Archive 1992

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: unions


Zdravko Balorda <zdravc at robo.fer.yu> writes:

  Given n closed intervals find their Union. For instance:
  [0,2];[2,4];[1,5]
  The union of the above 3 intervals would be [0,5].

  The union of the following:
  [0,2];[3,5]
  would be [0,2][3,5].

  The algorithm goes like this: 
  1. Sort all the intervals
  2. Find unions of all adjacent pairs
  3. Repeat step 2 while the result is changing.

  Could anyone make any suggestions on real Mma code for that?

Your algorithm seems as good as any.  Here it is in Mathematica code:

  In[34]:= intervalunion [ listofintervals_ ] :=
           Sort[listofintervals] //. {a___, {b_,c_}, {d_,e_}, f___} :>
                                     {a, {b,e}, f} /; c >= d;

  In[35]:= intervalunion[ { {3,5}, {1,4} } ]

  Out[35]= {{1, 5}}

  In[36]:= intervalunion[ { {1,4}, {3,5}, {-1,0}, {6,7}, {1,2}, {7,9} } ]

  Out[36]= {{-1, 0}, {1, 5}, {6, 9}}

Jack Lee
Dept. of Mathematics
University of Washington
Seattle, WA 98105






  • Prev by Date: speedups
  • Next by Date: Re: non-linear fitting of data
  • Previous by thread: Re: Eigenvalue problems in diff equations.
  • Next by thread: Re: Unions