Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split an array into multiple arrays in random order - Ruby

I am trying to split an array of names into multiple arrays in random order each time it is run. I know how to split them with:

 name_array = ["bob","john","rob","nate","nelly","michael"]
 array = name_array.each_slice(2).to_a
 => [["bob", "john"], ["rob", "nate"], ["nelly", "michael"]]

But, what if I want it to spit them out in random order each time?

like image 865
Nate Beers Avatar asked Aug 05 '14 15:08

Nate Beers


3 Answers

Before do the same thing, shuffle the array. (Array#shuffle)

name_array.shuffle.each_slice(2).to_a
# => [["nelly", "nate"], ["rob", "bob"], ["michael", "john"]]

or, shuffle afterward according to your need:

name_array.each_slice(2).to_a.shuffle
# => [["nelly", "michael"], ["rob", "nate"], ["bob", "john"]]
like image 173
falsetru Avatar answered Sep 28 '22 10:09

falsetru


Random Sampling

If you know the size of the original array, then:

name_array.sample 6

Array#sample shortens your method chain over the use of Array#shuffle. If you don't want to hard-code the size of the sample, you can introspect the array for its size at run-time. For example:

name_array.sample(name_array.size)

Permutation

If you don't need to insist that a given name appears only once in your result set, then you might also consider Array#permutation:

name_array.permutation(2).to_a.sample(name_array.size)

The results will vary, but here's a pretty-printed sample of the results you might expect from this approach:

[["michael", "rob"],
 ["bob", "nelly"],
 ["rob", "bob"],
 ["michael", "nelly"],
 ["john", "michael"],
 ["john", "rob"]]
like image 35
Todd A. Jacobs Avatar answered Sep 28 '22 09:09

Todd A. Jacobs


Shuffle the array first, then slice:

["bob","john","rob","nate","nelly","michael"].shuffle.each_slice(2).to_a
#=> [["nelly", "nate"], ["rob", "michael"], ["john", "bob"]]
like image 45
Grych Avatar answered Sep 28 '22 09:09

Grych