Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent identical pairs when shuffling and slicing Ruby array

I'd like to prevent producing pairs with the same items when producing a random set of pairs in a Ruby array.

For example:

[1,1,2,2,3,4].shuffle.each_slice(2).to_a

might produce:

[[1, 1], [3, 4], [2, 2]]

I'd like to be able to ensure that it produces a result such as:

[[4, 1], [1, 2], [3, 2]]

Thanks in advance for the help!

like image 857
Ron M Avatar asked Mar 14 '26 04:03

Ron M


1 Answers

arr = [1,1,2,2,3,4]
loop do
  sliced = arr.shuffle.each_slice(2).to_a
  break sliced if sliced.none? { |a| a.reduce(:==) }
end
like image 125
Aleksei Matiushkin Avatar answered Mar 15 '26 20:03

Aleksei Matiushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!