小编Ven*_*tta的帖子

河内的塔:Ruby中的递归解释

注意:我理解递归解决方案; 但我不知道代码是如何实现的,因为我无法按照代码执行的步骤进行操作.

我很难理解河内塔的递归循环.我已经评论并尝试了各种策略来了解程序是如何运作的,但我似乎无法掌握循环如何运作以及环如何被引导.

  def move(rings, from, destination, other)
    if rings == 1
      ring = from.pop
      p "Move ring #{ring} from #{from} to #{destination}"
      destination.push ring
    else
      move(rings-1, from, other, destination)
      move(1, from, destination, other)
      move(rings-1, other, destination, from)
    end
  end
Run Code Online (Sandbox Code Playgroud)

这是输出:

"Move ring 1 from a to c"
"Move ring 2 from a to b"
"Move ring 1 from c to b"
"Move ring 3 from a to c"
"Move ring 1 from b to a"
"Move ring 2 from …
Run Code Online (Sandbox Code Playgroud)

ruby recursion towers-of-hanoi

2
推荐指数
1
解决办法
2365
查看次数

标签 统计

recursion ×1

ruby ×1

towers-of-hanoi ×1