def shuffle arr
shuffled = []
while arr.length > 0
randNum = rand(arr.length)
idx = 0
unshuf = []
print '--- arr='; p arr # <--------
arr.each do |item|
if idx == randNum
shuffled.push item
else
unshuf.push item
end
print 'shuffled='; print shuffled; print ', unshuf='; p unshuf # <--------
idx = idx + 1
end
arr = unshuf
end
return shuffled
end
p shuffle([ 11, 12, 13, 14, 15])
执行 :
$ ruby -w t.rb
--- arr=[11, 12, 13, 14, 15]
shuffled=[], unshuf=[11]
shuffled=[], unshuf=[11, 12]
shuffled=[13], unshuf=[11, 12]
shuffled=[13], unshuf=[11, 12, 14]
shuffled=[13], unshuf=[11, 12, 14, 15]
--- arr=[11, 12, 14, 15]
shuffled=[13, 11], unshuf=[]
shuffled=[13, 11], unshuf=[12]
shuffled=[13, 11], unshuf=[12, 14]
shuffled=[13, 11], unshuf=[12, 14, 15]
--- arr=[12, 14, 15]
shuffled=[13, 11, 12], unshuf=[]
shuffled=[13, 11, 12], unshuf=[14]
shuffled=[13, 11, 12], unshuf=[14, 15]
--- arr=[14, 15]
shuffled=[13, 11, 12, 14], unshuf=[]
shuffled=[13, 11, 12, 14], unshuf=[15]
--- arr=[15]
shuffled=[13, 11, 12, 14, 15], unshuf=[]
[13, 11, 12, 14, 15]
解释: 的内容arr
在 shuffled 和 unshuf 之间随机分布。然后 unshuf 替换 arr ,如果 unshuf 中有什么东西,while 循环会随机重新分配一点点 shuffle,一点点 unshuf。依此类推,直到 unshuf 为空。所以 shuffled 逐渐填充从arr
最初给方法的参数中随机获取的元素shuffle
,但arr
也通过只保留 unshuf 元素逐渐清空arr = unshuf
。当然,在移入 arr 后,unshuf 必须重置为空数组才能接收新的分布,而 shuffled 必须保持增长。希望很清楚。