2014-04-30 48 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)確保最後一個元素永遠不會被選中。