【问题标题】:Bug in Ruby code for permutations algorithm?用于排列算法的 Ruby 代码中的错误?
【发布时间】: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


【解决方案1】:

你能发光吗?

让我试试。

想象一下,您想要一份包含各种有趣身体姿势的目录。所以你得到这个模型,Cindy,让她单腿站立。然后你让她鼓起脸颊,把手放在下巴下面。然后,另外十几个职位。最后,你请她鞠躬。

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

但是,如果您在每个姿势下拍摄 Cindy 的图像,您现在就有了一个包含不同 Cindy 姿势的图库。

clone 应该会给你一个非常逼真的 Cindy 形象。这样,即使原来的 Cindy 换了一个姿势,你仍然有克隆的 Cindy 来显示之前的姿势。

您的 array 是 Cindy。您将相同的array 多次添加到$permutations,并在两者之间进行更改;但是$permutations 中的每个条目都是同样可怜的array。无论您查看哪种排列,它都将是 array 最后的任何姿势。您需要多个不同 arrays,clone 将为您制作它们 - 对克隆时 array 的任何内容进行快照,留下 array 去下一个姿势不会丢失之前的记录。

【讨论】:

  • 优秀的答案。非常感谢。当我更多地考虑这个问题时,我认为你的解释一定是原因。
猜你喜欢
  • 2016-04-20
  • 1970-01-01
  • 1970-01-01
  • 2015-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多