I have the code below:
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]))
I am trying to understand the status of the array unshuf as the method shuffle is called. The array unshuf is being reset to an empty array each time before method each is called. Under such implementation, how are the numbers pushed into unshuf retained for the next round of if condition?
Execution :
Explanation : the content of
arris randomly distributed between shuffled and unshuf. Then unshuf replaces arr and, if there was something in unshuf, the while loop redistributes randomly a little in shuffle, a little in unshuf. And so on until unshuf is empty. So shuffled is progressively filled with elements randomly taken from the parameterarrinitially given to the methodshuffle, butarris also progressively emptied by keeping only unshuf elements inarr = unshuf. Of course after having been moved into arr, unshuf must be reset to an empty array to receive the new distribution, while shuffled must keep growing. Hope it’s clear.