2014-04-30 47 views
0

我在下面的代码有一些问题。这很简单,但对我来说最尴尬的是它确实有效。红宝石 - 虽然循环循环,当我相信它不应该

在这里,我们有一个程序,洗牌先前输入数组中的项目,并将其打印到屏幕上。而已。

现在,为什么我这么奇怪? 所有归结为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重复只有两次,为什么?

因为首先我们的y0,并且它的数量小于1。所以在这里我们有我们的第一个 通过我们的循环。 现在是第二次穿越循环的时间,y = 1,count = 1,它们是平等的,我们走吧。 现在它正在做第三次演练。而y = 2count = 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 
+0

为什么要计数改变?它看起来并不像它在这个while循环中改变(假设这是一组顶级的方法,而不是阵列上的猴子补丁) –

+1

*“按'输入'退出”* - 列表中的最后一项'总是一个空的字符串,也许这是造成混乱? – Stefan

+0

是的,我没有注意到当你离开空白处并按回车键时,你实际上将它添加到数组中。感谢您的帮助。 – Matthew

回答

0

你是正确的,计数是1与array = ["a","b","c"]

但是,当你这样做:

while word != '' 
    word = gets.chomp 
    list.push word 
end 

你实际上得到一个array = ["a","b","c",""]。因此,计数实际上是2.

这不会在以后导致问题,因为x = rand(count+1)确保最后一个元素永远不会被选中。