开发者

Shuffling a list in Mathematica

开发者 https://www.devze.com 2023-03-04 03:04 出处:网络
What\'s the best/easiest way to shuffle a lon开发者_开发知识库g list in Mathematica?RandomSample[list]

What's the best/easiest way to shuffle a lon开发者_开发知识库g 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.


Currently I use

list[[PermutationList@RandomPermutation@Length[list]]]

This is for Mathematica 8. Combinatorica also has a RandomPermutation function (earlier versions).

I am looking for other/better solutions, if there are any.

0

精彩评论

暂无评论...
验证码 换一张
取 消