我改變了我在網上找到的一些代碼,但是我的版本將集合中的最後一個詞典排列賦給了集合的所有元素。誰能告訴我爲什麼?這裏是我的代碼:用於排列算法的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]]
在此先感謝您的幫助!
您每次都重新使用相同的數組對象。將'$ permutations.push數組'改爲'$ permutations.push array.clone' –
謝謝!修復它。我顯然是一個小白菜,我不明白爲什麼這會奏效。你能照亮嗎? – Ice101781
@NeilSlater:這是一個答案:) – quetzalcoatl