I’m trying to visualize a simple Hanoi solver that uses an algorithm, and I’m swapping elements on array to visualize it.
Here’s my code:
let A = ();
let B = ();
let C = ();
let moveCount = 0;
let once = true;
hanoi(3, A, C, B);
// 3, how many disk
// A C B are rods
alert(A + '.n' + B + '.n' + C + '.')
function hanoi(n, start, target, other)
{
if (once)
{
once = false;
for (var i = 1; i <= n; i--)
{
start.push(i);
}
}
if (n <= 1)
{
let temp = start(n-1);
start(n-1) = target(target.length);
start = start.filter(Boolean)
target(target.length) = temp;
target = target.filter(Boolean);
//console.log('Moving disk '+n+' from rod '+start+' to '+target+' rod');
moveCount++;
}
else
{
hanoi(n-1, start, other, target);
let temp = start(n-1);
start(n-1) = target(target.length);
start = start.filter(Boolean)
target(target.length) = temp;
target = target.filter(Boolean);
//console.log('Moving disk '+n+' from rod '+start+' to rod '+target);
moveCount++;
hanoi(n-1, other, target, start);
}
}
The C value should be expected (3, 2, 1)
but only shows 2. I also checked A and B and 1 is nowhere to be found
How do I make this properly so the output would be (3, 2, 1)
Imagine 3 is the largest disk and so on…