2014-06-09 26 views
-3

我改變了我在網上找到的一些代碼,但是我的版本將集合中的最後一個詞典排列賦給了集合的所有元素。誰能告訴我爲什麼?這裏是我的代碼:用於排列算法的Ruby代碼中的錯誤?

$permutations = [] 

def perms(array) 
    $permutations.push array 

    #handle the case when the length of 'array' is one or less 
    if array.length <= 1 
    return $permuations 
    end 

    #find the first element less than the one following it 
    i = (array.length - 2) 
    until array[i] < array[i+1] 
    i = (i - 1)  
    end 

    #if the array is in descending order, we've finished 
    if i < 0 
    return $permutations 
    end 

    #identify the first element larger than 'i' 
    j = (array.length - 1) 
    until array[j] > array[i] 
    j = (j - 1) 
    end 

    #swap the 'ith' and 'jth' elements 
    array[i], array[j] = array[j], array[i] 

    #reverse the list from 'i + 1' to the end 
    i = (i + 1) 
    j = (array.length - 1) 
    until j < i 
    array[i], array[j] = array[j], array[i] 
    i += 1 
    j -= 1 
    end 

    #run the method again, with the newest permutation as the seed 
    perms(array) 
end 

#test the method 
perms([0, 1, 2]) 
print $permutations 

我得到的輸出是:[2,1,0],[2,1,0],[2,1,0],[2,1,0 ],[2,1,0],[2,1,0]]

在此先感謝您的幫助!

+1

您每次都重新使用相同的數組對象。將'$ permutations.push數組'改爲'$ permutations.push array.clone' –

+0

謝謝!修復它。我顯然是一個小白菜,我不明白爲什麼這會奏效。你能照亮嗎? – Ice101781

+1

@NeilSlater:這是一個答案:) – quetzalcoatl

回答

0

你能照亮嗎?

讓我試試。

想象一下,你想擁有各種有趣的身體姿勢的目錄。所以,你得到這個模型,辛迪,並讓她站在一條腿上。然後,你問她吸吮她的臉頰,並把手放在她的下巴下。然後,還有十多個職位。最後,你問她要鞠躬。

最後,你沒有15個不同的Cindys,每個Cindys都有不同的姿勢。你只有一個,目前正在鞠躬。但是,如果您在每個姿勢中都拍攝了Cindy的圖像,則您現在將擁有不同Cindy姿勢的畫廊。

clone應該給你一個非常逼真的辛迪形象。這樣,即使原始辛迪採取另一種姿勢,你仍然有克隆辛迪顯示以前的姿勢。您的array是辛迪。你多次添加相同的array$permutations,並在兩者之間進行更改;但是$permutations中的每個條目都是那個差array。無論你看到什麼樣的排列組合,它最終都會以最後的形式出現在array之中。您需要不同的array s和clone會爲您製作它們 - 拍攝克隆時array的快照,並讓array轉到下一個姿勢,而不會丟失前一個的記錄。

+0

優秀的答案。非常感謝。當我更多地考慮這個問題時,我認爲你的解釋必定是原因。 – Ice101781