//////// Towers of Hanoi Iterative
function HanoiIterative(n) {
const trackDiskPosition = Array(n).fill(0);
for (let stepCount = 0; stepCount < 2 ** n; ++ stepCount) {
for (let currentDisk = 0; currentDisk < n; ++ currentDisk) {
const expectedPosition = count(currentDisk, stepCount);
if (trackDiskPosition[currentDisk] !== expectedPosition) {
console.log(`Move disk ${currentDisk + 1} from ${trackDiskPosition[currentDisk] + 1} to ${expectedPosition + 1}`);
trackDiskPosition[currentDisk] = expectedPosition;
break;
}
}
}
}
function count(disk, step) {
let temp = Math.ceil(
(step + (disk % 2 === 1 ? 2 ** (disk + 2) : 0) - 2 ** disk + 1)
/ (2 ** (disk + 1))
) % 3;
return disk % 2 === 1 ? 2 - temp : temp;
}
///////// Towers of Hanoi Recursive
function HanoiRecursive(n, a, b, c) {
if (n > 0) {
HanoiRecursive(n-1, a, c, b);
console.log("Move disk from " + a + " to " + c);
HanoiRecursive(n-1, b, a, c);
}
}
console.log("
Iterative = ");
HanoiIterative(3)
console.log("Recursive = ");
HanoiRecursive(3, "1", "2", "3");