What's the best/easiest way to shuffle a long list in Mathematica?
RandomSample[list]
Yes, it's really that simple. At least since version 6.
Before RandomSample
was introduced, one might use:
#[[ Ordering[Random[] & /@ #] ]] & @ list
Before RandomSample was introduced, I've used the below MathGroup-function heavily, though RandomSample is faster at least by one magnitude on my machine.
In[128]:= n = 10;
set = Range@n
Out[129]= {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
In[130]:= Take[set[[Ordering[RandomReal[] & /@ Range@n]]], n]
Out[130]= {8, 4, 5, 2, 3, 10, 7, 9, 6, 1}
Other problem besides performance is that if the same random reals are hit twice (improbable, though possible) Ordering will not give these two in random order.
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