From: Jim Haungs Date: 2004-07-12T01:17:26+09:00 Subject: Re: A little algorithmic help requested... Here's an iterator approach. The maximum group size and the splitting criterion can be parameterized. def groups(anArray, split) list = [] anArray.each do | n | if list.empty? or split[list.last, n] list << n else yield list list = [n] end end yield list end def ranges(anArray, maxGroupSize, split) groups(anArray, split) do | group | if group.size > maxGroupSize then yield group else group.each {|g| yield [g]} end end end test = [1,2,3,4,6,7,8,11,12,15,16,17,18] maxGroupSize = 2 criterion = proc{|x,y| x.succ == y} ranges(test, maxGroupSize, criterion) { | range | p range } [1, 2, 3, 4] [6, 7, 8] [11] [12] [15, 16, 17, 18] On Sun, 11 Jul 2004 16:10:34 +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? > > >Thanks, >Hal > >