Home  >  Q&A  >  body text

javascript - Ask about the Tower of Hanoi algorithm

JS uses recursion to implement the steps to complete the Tower of Hanoi. I believe many students can do it.
I wrote a Tower of Hanoi game in my spare time. There is a reminder function in it. When the user clicks the reminder, the program uses recursion to implement a completion step, and then operates the page elements to implement it according to this step.
Partial code is as follows:

var moves = [];  // 存放完成步骤
/**
 * @param disc      当前关卡 (实际上也就是圆盘数量)
 * @param discs1    第一根圆柱
 * @param discs2    第二根圆柱
 * @param discs3    第三根圆柱
 */
function hanoiArithmetic(disc, discs1, discs2, discs3) {
    if (disc > 0) {
        hanoiArithmetic(disc - 1, discs1, discs3, discs2);
        moves.push(discs1 + '>' + discs3);
        hanoiArithmetic(disc - 1, discs2, discs1, discs3);
    }
}
hanoiArithmetic(4, 'discs1', 'discs2', 'discs3');
console.log(moves); 
// 最后得到这样一个步骤列表
[ 'discs1>discs3',
  'discs1>discs2',
  'discs3>discs2',
  'discs1>discs3',
  'discs2>discs1',
  'discs2>discs3',
  'discs1>discs3' ] // 大概意思就是想从第一个圆柱取最上面那个圆盘放到第三个圆柱...

Everything is fine. The problem now is that this can only be a new level. A step list is generated when the user has not moved any disks. If the user has moved the disks, such as now There are 3 discs on the first cylinder, 2 discs on the second, and 1 disc on the third. The user is stumped and doesn’t know what to do next. At this time, click reminder, How to generate subsequent step algorithms based on the current situation?
I feel ashamed to say that this game was written half a year ago. So far, the reminder function has not been completed, and I have no clue at all.

漂亮男人漂亮男人2710 days ago2601

reply all(2)I'll reply

  • phpcn_u1582

    phpcn_u15822017-05-19 10:45:07

    You can look at the Fibonacci sequence for this. The Tower of Hanoi is the Fibonacci algorithm

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-19 10:45:07

    If you need such a reminder function, it is a bit more complicated than what you have now, and you need to record the status.
    For example, in your example, there are 6 discs, and there are 3 discs on the first pillar. It may be 456, or it may be 135. You need to clarify the current status, then complete the steps and then decompose it from top to bottom.

    if 最大圆盘不在目标圆柱上 {
      if 最大圆盘不能直接移动到目标圆柱 {
        其他圆盘移动到“中间”圆柱(规模减一)  //非最大圆盘所在圆柱和目标圆柱
      } 
      移动最大圆盘到目标圆柱
    }
    移动其他圆盘到目标圆柱(规模减一)

    reply
    0
  • Cancelreply