【发布时间】:2015-08-31 01:01:34
【问题描述】:
我正在解决 Ruby 中的一个玩具问题:如何生成所有可能的 10 位电话号码,其中每个连续的号码都与键盘上的最后一个号码相邻。我已经表示了数字之间的相邻关系,并且有一个递归函数,但是我的方法并没有遍历整个解决方案空间。它只是找到第一个解决方案并返回。
这是我的代码:
adjacencies = { 1 => [2, 4],
2 => [1, 3, 5],
3 => [2, 6],
4 => [1, 5, 7],
5 => [2, 4, 6, 8],
6 => [3, 5, 9],
7 => [4, 8],
8 => [5, 7, 9, 0],
9 => [6, 8],
0 => [8]
}
def append_number(partial_phone_number, to_append, adjacencies)
phone_length = 10
partial_phone_number = partial_phone_number + to_append.to_s
if (partial_phone_number.length == phone_length)
return partial_phone_number
else
adjacencies[to_append].each do |a|
return append_number(partial_phone_number, a, adjacencies)
end
end
end
(0..9).each do |n|
puts append_number("", n, adjacencies)
end
这是我运行它时的输出:
0852121212
1212121212
2121212121
3212121212
4121212121
5212121212
6321212121
7412121212
8521212121
9632121212
【问题讨论】:
-
看起来你告诉它执行 10 次 (0..9) 而它执行了 10 次?
-
我不知道关于 ruby 的第一件事,但是如果这部分 [adjacencies[to_append].each 做 |a| return append_number(partial_phone_number, a, adjacencies)] 不是所有相邻数字的 for,那么应该是!
-
@AshkanKzme 是——我查过了。
-
您能说说预期的输出吗?
-
这是一个要点,我修改后的代码现在可以正常运行,但会产生重复的值,然后我使用 Array#uniq 将其删除:gist.github.com/bee4eab8243ee22ea488
标签: ruby algorithm search recursion