From: Harry Kakueki Date: 2009-09-02T18:20:51+09:00 Subject: Re: Nice algorithm for 'spreading' indexes across an array? On Wed, Sep 2, 2009 at 5:30 PM, Max Williams wrote: > Thanks, everyone. Harry, i like your solution but i thought of a way to > tweak it in a way which seems more readable, to me at least: > > class Array > def spread(num) > discarded = [] > (1..(size-num)).each{|u| discarded << self[size*u/(size-num+1)]} > self - discarded > end > end > > The clever bit is of course line 4. I'm still trying to work out why > that works :) > That is not exactly the same thing. But it depends on your specs. class Array def spread(num) res,idue = [],[] (1..(size-num)).each{|u| idue << size*u/(size-num+1)} (0...size).each{|y| res << self[y] if idue.include?(y) == false} res end def spread2(num) discarded = [] (1..(size-num)).each{|u| discarded << self[size*u/(size-num+1)]} self - discarded end end arr = [1,2,3,4,5,6,7,8,9,9,10,11,12] (3..13).each{|t| p arr.spread(t)} puts (3..13).each{|t| p arr.spread2(t)} ############output #=> [1, 7, 12] #=> [1, 5, 9, 12] #=> [1, 4, 7, 9, 12] #=> [1, 3, 6, 8, 10, 12] #=> [1, 3, 5, 7, 9, 10, 12] #=> [1, 2, 4, 6, 8, 9, 11, 12] #=> [1, 2, 4, 5, 7, 9, 9, 11, 12] #=> [1, 2, 3, 5, 6, 8, 9, 10, 11, 12] #=> [1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12] #=> [1, 2, 3, 4, 5, 6, 8, 9, 9, 10, 11, 12] #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 10, 11, 12] #=> [1, 7, 12] #=> [1, 5, 12] #=> [1, 4, 7, 12] #=> [1, 3, 6, 8, 10, 12] #=> [1, 3, 5, 7, 10, 12] #=> [1, 2, 4, 6, 8, 11, 12] #=> [1, 2, 4, 5, 7, 9, 9, 11, 12] #=> [1, 2, 3, 5, 6, 8, 10, 11, 12] #=> [1, 2, 3, 4, 6, 7, 8, 10, 11, 12] #=> [1, 2, 3, 4, 5, 6, 8, 9, 9, 10, 11, 12] #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 10, 11, 12] Harry -- A Look into Japanese Ruby List in English http://www.kakueki.com/ruby/list.html