//function to solve the towers of hanoi problem
function solveTowers(n, fromPeg, toPeg, tempPeg) {
//if n is 1, move the disk from fromPeg to toPeg
if (n === 1) {
console.log(`Move disk 1 from ${fromPeg} to ${toPeg}`);
return;
}
//solve the towers of hanoi problem for n - 1
solveTowers(n - 1, fromPeg, tempPeg, toPeg);
//move the nth disk from fromPeg to toPeg
console.log(`Move disk ${n} from ${fromPeg} to ${toPeg}`);
//solve the towers of hanoi problem for n - 1
solveTowers(n - 1, tempPeg, toPeg, fromPeg);
}
//example
solveTowers(3, "A", "B", "C");
//output
/*
Move disk 3 from A to C
Move disk 2 from A to B
Move disk 1 from A to C
Move disk 3 from B to A
Move disk 1 from B to C
Move disk 2 from A to C
*/
For further actions, you may consider blocking this person and/or reporting abuse
Oldest comments (0)