How can I solve this issue of the Hanoi Tower without using recursive?

180 Views Asked by At

I tried to solve the tower of Hanoi with non-recursive, but an error occurred. Could you give me a favor? If possible, I want to know the solution by javascript.

This is my code with an error:

const hanoi = (n) => {
  const sign = ["a", "b", "c"];
  const path = [];
  let beforePile = 0;
  while (n--) {
    const nextPile = 1 + ((n + 1) % 2);
    path.push([0, nextPile]);
    const tmp = path;
    for (let i = 0; i < tmp.length - 1; i++)
      path.push([(path[i][0] + beforePile) % 3, (path[i][1] + beforePile) % 3]);
    beforePile = nextPile;
  }
  path.forEach((i) => {
    console.log(sign[i[0]] + " -> " + sign[i[1]]);
  });
};

hanoi(3);

( 'a' : start, 'c': destination )

1

There are 1 best solutions below

0
On

When you have a look on the paths of this problem, it has a rule. In order to move n of pegs from 'a' to 'c', move n-1 of pegs from 'a' to 'b' then move a peg from 'a' to 'c'. Then move n-1 of pegs from 'b' to 'c'. So the paths between moving 'a' to 'b' and moving 'b' to 'c' is very similar. But all of the alphabets only differ 1 distance. This is the key, i think.

const hanoi = (n) => {
  const sign = ["a", "b", "c"];
  const path = [];
  let beforePile = 0;
  while (n--) {
    const nextPile = 1 + ((n + 1) % 2);
    path.push([0, nextPile]);
    const tmp = path.length;
    for (let i = 0; i < tmp - 1; i++)
      path.push([(path[i][0] + beforePile) % 3, (path[i][1] + beforePile) % 3]);
    beforePile = nextPile;
  }
  path.forEach((i) => {
    console.log(sign[i[0]] + " -> " + sign[i[1]]);
  });
};

hanoi(3);