I have multiple arrays in ruby of variable length from 1 to 40 :
@items is a typical array which could be anywhere from 1 to 40 in length. eg
@items = [1, 2, 3, 4, 5, 6]
I want to randomly split the array into smaller arrays of lengths either 1, 2 or 3 to give a result of (for example)
@items = [[1, 2],[3],[4,5,6]]
or
@items = [[1],[2, 3],[4],[5,6]]
etc
I know you can split the array using @items.each_slice(3)... where 3 is a fixed length. But i want to randomly split large arrays of variable length into array sizes of 1,2 or 3 randomly... Whats the best way to achieve this?
items, @items = @items.dup, []
@items.push(items.shift(rand(1..3))) until items.empty?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With