From: "Jesús Gabriel y Galán" Date: 2009-09-02T02:44:04+09:00 Subject: Re: Nice algorithm for 'spreading' indexes across an array? On Tue, Sep 1, 2009 at 6:41 PM, Max Williams wrote: > Little ruby algorithm puzzle... > > I have a situation where i have an array of 12 items.  If someone > chooses to have n of them (where n can be between 3 and 12) then i want > to always include the first and last, and then 'spread' the others out > as evenly as possible between the rest. > > So, lets say for the sake of argument that the array holds the numbers 1 > to 12. > >>> 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? Here's my try. It fails when the number you are asking for is more than half the size, but anyway, it might give you an idea: class Array def spread how_many result = [] each_slice(size / (how_many - 1)) { |a, *_| result << a} result << self[-1] result end end irb(main):004:0> load 'spread.rb' => true irb(main):005:0> (1..12).to_a.spread 3 => [1, 7, 12] irb(main):006:0> (1..12).to_a.spread 4 => [1, 5, 9, 12] irb(main):007:0> (1..12).to_a.spread 12 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 12] irb(main):008:0> (1..12).to_a.spread 11 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 12] irb(main):019:0> (1..12).to_a.spread 8 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 12] Jesus.