Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffling a list in Mathematica

What's the best/easiest way to shuffle a long list in Mathematica?

like image 512
Szabolcs Avatar asked May 09 '11 10:05

Szabolcs


2 Answers

RandomSample[list]

Yes, it's really that simple. At least since version 6.

Before RandomSample was introduced, one might use:

#[[ Ordering[Random[] & /@ #] ]] & @ list
like image 186
Mr.Wizard Avatar answered Oct 06 '22 15:10

Mr.Wizard


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.

like image 40
István Zachar Avatar answered Oct 06 '22 15:10

István Zachar