题
什么是Ruby中返回以随机顺序阵列的最简单的方法? 凡是是可以在一个IRB会话中使用像
好和短[1,2,3,4,5].random()
# or
random_sort([1,2,3,4,5])
解决方案
如果您还没有[] .shuffle,[] {.sort_by兰特}工作由sepp2k指出。 .sort_by的东西临时替换每个元件的分类,在这种情况下,随机数的目的。
[]。{排序兰特-0.5}但是,将不能正确洗牌。有些语言(例如,一些JavaScript实现)不正确洗牌数组,如果你做的阵列上的随机排序,与有时相当公开的后果。
JS分析(使用图形!): HTTP: //www.robweir.com/blog/2010/02/microsoft-random-browser-ballot.html
Ruby是没有什么不同!它有同样的问题。 :)
#sort a bunch of small arrays by rand-0.5
a=[]
100000.times{a << [0,1,2,3,4].sort{rand-0.5}}
#count how many times each number occurs in each position
b=[]
a.each do |x|
x.each_index do |i|
b[i] ||=[]
b[i][x[i]] ||= 0
b[i][x[i]] += 1
end
end
p b
=>
[[22336, 18872, 14814, 21645, 22333],
[17827, 25005, 20418, 18932, 17818],
[19665, 15726, 29575, 15522, 19512],
[18075, 18785, 20283, 24931, 17926],
[22097, 21612, 14910, 18970, 22411]]
应发生在大约20000次的各位置中的每个元素。 [] .sort_by(RAND)给出更好的结果。
#sort with elements first mapped to random numbers
a=[]
100000.times{a << [0,1,2,3,4].sort_by{rand}}
#count how many times each number occurs in each position
...
=>
[[19913, 20074, 20148, 19974, 19891],
[19975, 19918, 20024, 20030, 20053],
[20028, 20061, 19914, 20088, 19909],
[20099, 19882, 19871, 19965, 20183],
[19985, 20065, 20043, 19943, 19964]]
类似地,对于[] .shuffle(这可能是最快)
[[20011, 19881, 20222, 19961, 19925],
[19966, 20199, 20015, 19880, 19940],
[20062, 19894, 20065, 19965, 20014],
[19970, 20064, 19851, 20043, 20072],
[19991, 19962, 19847, 20151, 20049]]
其他提示
array.shuffle
不隶属于 StackOverflow