我有以下代码:
def shuffle arr
shuffled = []
while arr.length > 0
randNum = rand(arr.length)
idx = 0
unshuf = []
arr.each do |item|
if idx == randNum
shuffled.push item
else
unshuf.push item
end
idx = idx + 1
end
arr = unshuf
end
return shuffled
end
puts(shuffle([ 11, 12, 13]))
我正试图理解数组
unshuf
的状态,因为调用方法shuffle
每次调用方法unshuf
之前,都会将数组each
重置为空数组。在这种实现方式下,如何为下一轮的unshuf
条件保留推入if
的数字? 最佳答案
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
的内容在无序和非无序之间随机分布。然后unshuf替换arr,如果unshuf中有什么东西,while循环会在shuffle中随机重新分配一点,在unshuf中随机重新分配一点等等,直到unsuf为空因此,shuffled是由最初给方法的参数arr
中随机抽取的元素逐步填充的,但是shuffle
也是通过只保留arr
中的unsurf元素而逐步清空的当然,在移动到arr之后,unsuf必须重置为空数组才能接收新的分发,而shuffled必须保持增长希望一切都清楚。关于ruby - 用每种方法在Ruby中排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14095273/