Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the best way to split an array in ruby into multiple smaller arrays of random size

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?

like image 712
Ryan Perera Avatar asked Dec 15 '22 12:12

Ryan Perera


1 Answers

items, @items = @items.dup, []
@items.push(items.shift(rand(1..3))) until items.empty?
like image 50
sawa Avatar answered May 18 '23 13:05

sawa