From: Jeffrey Dik Date: 2004-07-11T17:22:50+09:00 Subject: Re: A little algorithmic help requested... On Sun, Jul 11, 2004 at 04:10:34PM +0900, Hal Fulton wrote: > Here's a problem my tired brain is having trouble with. > > Given a sorted array of integers, convert them into as many > ranges as possible (ranges of three or more). > > Example: > [1,2,3,4,6,7,8,11,12,15,16,17] ==> [1..4,6..8,11,12,15..17] > > How would *you* do this? At 4:20am, I'd do it like this a = [1,2,3,4,6,7,8,11,12,15,16,17] def to_ranges(a) ranges = [a[0]..a[0]] a.shift a.each_index { |i| if ranges.last.last + 1 == a[i] ranges[-1] = ranges.last.first..a[i] else ranges.push(a[i]..a[i]) end } ranges.map! { |r| case r.last-r.first when 0 r = r.first when 1 r = [r.first, r.last] end r } ranges.flatten end puts to_ranges(a) I'm guessing I'd do it differently at a some other time in the day :-) Sleepy time, Jeff > > > Thanks, > Hal > > >