这真让我抓狂!我一直在尝试编写一个 Ruby 方法来查找所有排列,以解决 Project Euler 的问题 24。当我交换数组的元素时,它们会正确交换。但是当我尝试将这个交换数组存储在一个不同的数组中时,这个新数组只记得我交换数组的最新副本!它不会记住旧版本。
当我在循环期间打印出 a 时,它会正确显示所有排列。但是当我打印出 perm (我用它来存储 a 的所有不同排列)时,它只显示一个重复多次的版本。我该如何解决?
a = [0, 1, 2, 3]
perms = []
p "a = #{a}" # output: "a = [0, 1, 2, 3]"
perms << a # add a to perms array
p "perms = #{perms}" # output: "perms = [[0, 1, 2, 3]]"
a[0], a[1] = a[1], a[0] # swap 1st 2 elements of a
p "a = #{a}" # output: "a = [1, 0, 2, 3]"
perms << a # add a to perms array
p "perms = #{perms}" # "perms = [[1, 0, 2, 3], [1, 0, 2, 3]]"
a[1], a[2] = a[2], a[1] # swap 2nd 2 elements of a
p "a = #{a}" # "a = [1, 2, 0, 3]"
perms << a # add a to perms array
p "perms = #{perms}" # "perms = [[1, 2, 0, 3], [1, 2, 0, 3], [1, 2, 0, 3]]"
感谢下面的 Sawa,“dup”和“clone”方法都解决了我的问题!为什么我原来的方法不起作用?我什么时候会使用“dup”与“clone”?请给我一些代码示例。
a[0], a[1] = a[1], a[0] # swap 1st 2 elements of a
p "a = #{a}" # output: "a = [1, 0, 2, 3]"
b = a.dup (or a.clone)
perms << b
p "perms = #{perms}" # "perms = [[0, 1, 2, 3], [1, 0, 2, 3]]" *** it remembers!
a[1], a[2] = a[2], a[1] # swap 2nd 2 elements of a
p "a = #{a}" # "a = [1, 2, 0, 3]"
b = a.dup (or a.clone)
perms << b
p "perms = #{perms}" # "perms = [[0, 1, 2, 3], [1, 0, 2, 3], [1, 2, 0, 3]]"