【发布时间】:2014-07-29 17:37:37
【问题描述】:
我更改了在网上找到的一些代码,但我的版本将集合中的最后一个词典排列分配给集合的所有元素。谁能告诉我这是为什么?这是我的代码:
$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 array更改为$permutations.push array.clone -
谢谢!解决了它。我显然是个菜鸟,我不明白为什么会这样。你能照亮吗?
-
@NeilSlater:这是一个答案:)
-
换句话说,如果我重复使用相同的程序,我会期望程序输出 [[0, 1, 2],...,[0, 1, 2]]每次数组对象;即数组 = [0, 1, 2]。但是程序确实运行了......为什么它推动了正确数量的排列,但全部 [2, 1, 0] ?
-
@quetzalcoatl:这个问题已经被问过很多次了。我会直接 OP o 例如stackoverflow.com/questions/2635156/… 以获得更多扩展答案,因为此排列代码中的特定错误不太可能是搜索词。另一种可能:stackoverflow.com/questions/1872110/…
标签: ruby algorithm permutation