It’s not specifically a ruby problem: more of a general question about algorithms. But there might be some ruby-specific array methods which are helpful.
I have an array with 30 items. I ask for a number of items between 15 and 30, and I want to select a given number of items from the whole array as evenly distributed as possible. The selection needs to be non-random, returning the same result every time.
Let’s say someone asks for 16 items. If I return the first 16, that would be a massive fail. Instead, I could return all the odd numbered ones plus the last one; If I had the numbers 1 to 30 stored in the array, I could give back
myArr.spread(16)
=> [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,30]
If someone asks for 20 items, its a bit tricker: I can’t immediately think of a nice programmatic way of doing this. I feel like it must have been solved already by someone. Any suggestions?
Divide the size of the array by the number of items you want to select (DON’T use truncating division) — this will be your “stride” as you walk over the array, selecting items. Keep adding the “stride” to a running total until it equals or exceeds the size of the array. Each time you add the “stride”, take the integral part and use it as an index into the array to select an item.
Say you have 100 items and you want to select 30. Then your “stride” will be 3.3333… so you start with a “running total” of 3.3333, and select item 3. Then 6.66666 — so you select item 6. Next is 10.0 — so you select item 10. And so on…
Test to make sure you don’t get “off by one” errors, and also that you don’t divide by zero if the array size or number of items to select is zero. Also use a guard clause to ensure that the number of items to select is not greater than the number in the array.