MathGroup Archive 2002

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

Search the Archive

Re: List processing


In article <aokbp7$afv$1 at smc.vnet.net>, John Leary <leary at paradise.net.nz> 
wrote:

>Greetings
>
>This problem can be solved by conventional programming, but I wonder if 
>there is an elegant Mathematica solution ?
>
>A list contains pairs of values, with each pair representing the lower and 
>upper edge of a sub-range.  Some of the sub-ranges partially overlap, some 
>fully overlap, others don't overlap at all.  The problem is to produce a 
>second list that contains the overall upper and lower edges of the 
>overlapping sub-ranges.
>
>A simple example :  {{100,200},{150,250},{120,270},{300,400}}  would result 
>in {{100,270},{300,400}}.
>
>In the real case, the input list has several hundred elements and the 
>output list typically has five elements.
>
>I have a working solution based on loops, but there must be a more elegant 
>one.  I would be very grateful for any suggestions.


Block[{data = {{100,200},{150,250},{120,270},
               {300,400}}},
  data = Sort[data,#[[1]]<#2[[1]]&];
  {{data[[1,1]],
    Fold[If[#<#2[[1]],#,Max[#,#2[[2]]]]&,
         data[[1,2]],Rest[data]]},
   {Fold[If[#>#2[[2]],#,Min[#,#2[[1]]]]&,
         (data=Reverse@data)[[1,1]],Rest[data]],
    data[[1,2]]}}]

-->
{{100, 270}, {300, 400}}

I haven't tested too extensively.  The so-called
"Mathematica way" is illustrated by the use of
Fold function to process data, without which you
must resort to conventional looping.

DH


  • Prev by Date: Re: List processing
  • Next by Date: Re: List processing
  • Previous by thread: Re: List processing
  • Next by thread: Re: List processing