From: Michael Neumann Date: 2004-07-12T02:09:47+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? require 'enumerator' def to_range(arr) ranges = [r=[]] arr.each_cons(2) {|a,b| r << a ranges << (r = []) if (b-a) != 1 r << b } ranges.map {|r| r.uniq! r.size > 2 ? (r.first..r.last) : r }.flatten end a = [1,2,3,4,6,7,8,11,12,15,16,17] p to_range(a) But no, I wouldn't do it this way. Regards, Michael