用于置换算法的Ruby代码中的错误?

时间:2014-06-09 07:49:00

标签: ruby algorithm permutation

我修改了我在网络上找到的一些代码,但是我的版本将集合中的最后一个字典排列分配给集合中的所有元素。谁能告诉我为什么会这样?这是我的代码:

$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 个答案:

答案 0 :(得分:0)

  你能点亮吗?

让我试试。

想象一下,你想拥有各种有趣身体姿势的目录。所以你得到这个模特,Cindy,让她站在一条腿上。然后你问她的脸颊,然后把手放在她的下巴下面。然后,另外十几个职位。最后,你要她鞠躬。

最后,你没有15个不同的Cindys,每个都有不同的姿势。你只有一个,目前正在鞠躬。

然而,如果你在每个姿势都拍摄了Cindy的图像,那么你现在有一个不同Cindy姿势的画廊。

clone应该给你一个非常逼真的辛迪形象。这样,即使最初的Cindy采取另一种姿势,你仍然有克隆的Cindy显示以前的姿势。

你的array是辛迪。您将array多次添加到$permutations,并在两者之间进行更改;但$permutations中的每个条目都是同一个穷人array。无论你看哪个排列,它都只是array最后的姿势。您需要一些不同的 arrayclone将为您制作它们 - 拍摄克隆时array所有内容的快照, array进入下一个姿势而不会丢失之前的记录。