From: Harry Kakueki Date: 2009-09-02T12:05:09+09:00 Subject: Re: Nice algorithm for 'spreading' indexes across an array? On Wed, Sep 2, 2009 at 1:41 AM, Max Williams wrote: > >>> arr = (1..12).to_a > => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] > > I would get results back like this > > arr.spread(3) > => [1,6,12] (or [1,7,12], either is fine) > > arr.spread(4) > => [1, 5, 9, 12] (or [1,4,8,12] or [1, 5, 8, 12]) > > It feels like there should be a simple solution for this but i can't > think of a nice way. Anyone? > > thanks > max > -- I haven't tested enough to see if this always works. But, take a look and make changes if necessary. class Array def spread(num) res,de = [],[] (1..(size-num)).each{|u| de << size*u/(size-num+1)} (0...size).each{|y| res << self[y] if de.include?(y) == false} res end end arr = (1..12).to_a (3..12).each{|t| p arr.spread(t)} #output #=> [1, 6, 12] #=> [1, 4, 8, 12] #=> [1, 3, 6, 9, 12] #=> [1, 3, 5, 8, 10, 12] #=> [1, 2, 4, 6, 8, 10, 12] #=> [1, 2, 4, 6, 7, 9, 11, 12] #=> [1, 2, 3, 5, 6, 8, 9, 11, 12] #=> [1, 2, 3, 4, 6, 7, 8, 10, 11, 12] #=> [1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12] #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] Harry -- A Look into Japanese Ruby List in English http://www.kakueki.com/ruby/list.html