我在下面的代码有一些问题。这很简单,但对我来说最尴尬的是它确实有效。红宝石 - 虽然循环循环,当我相信它不应该
在这里,我们有一个程序,洗牌先前输入数组中的项目,并将其打印到屏幕上。而已。
现在,为什么我这么奇怪? 所有归结为count
变量,y
变量和while loop
。 我解释这个代码对自己一步一步,仍然不知道它是如何可能这个程序到阵列中的最后一个项目分析,以及所有因
while y <= count
x = rand(count+1)
if array[x] != 'used'
randomized.push array[x]
array [x] = 'used'
y = y + 1
end
我只是不明白它。如果我创建一个有三个项目的数组 array = ["a","b","c"]
然后变量count
等于1
。并且y
变量等于0
在循环的开始和结尾我们增加y
通过1
。这while loop
应该只是在条件while y <= count
重复只有两次,为什么?
因为首先我们的y
是0
,并且它的数量小于1
。所以在这里我们有我们的第一个 通过我们的循环。 现在是第二次穿越循环的时间,y = 1
,count = 1
,它们是平等的,我们走吧。 现在它正在做第三次演练。而y = 2
和count = 1
。
有人可以解释我怎么可能?
# starting condition
list = [ ]
# as the question
puts 'Enter a list of words, press \'enter\' to quit and they will be returned
randomly shuffled.'
word = 'one'
# get the words in the first list
while word != ''
word = gets.chomp
list.push word
end
# define shuffle method
def shuffle array
# starting conditions of local variables
randomized = [ ]
count = -2
x = 0
y = 0
array.each do |word|
count = count + 1
end
while y <= count
x = rand(count+1)
if array[x] != 'used'
randomized.push array[x]
array [x] = 'used'
y = y + 1
end
end
puts randomized
end
shuffle list
为什么要计数改变?它看起来并不像它在这个while循环中改变(假设这是一组顶级的方法,而不是阵列上的猴子补丁) –
*“按'输入'退出”* - 列表中的最后一项'总是一个空的字符串,也许这是造成混乱? – Stefan
是的,我没有注意到当你离开空白处并按回车键时,你实际上将它添加到数组中。感谢您的帮助。 – Matthew