JavaScript: Implement the Tower of Hanoi Algorithm

1. Introduction

The Tower of Hanoi is a classic puzzle that involves moving a series of disks from one peg to another, with the constraint that a larger disk can never be placed on top of a smaller disk.

2. Program Overview

In this JavaScript program, we'll create a recursive function to solve the Tower of Hanoi problem. The function will print out the steps to solve the puzzle.

3. Code Program

// The Tower of Hanoi function
function towerOfHanoi(n, sourcePeg, targetPeg, auxiliaryPeg) {
    // Base case: If there's only one disk, move it and return
    if (n === 1) {
        console.log("Move disk 1 from peg " + sourcePeg + " to peg " + targetPeg);
        return;
    }
    // Move the top n-1 disks from the source peg to the auxiliary peg using the target peg
    towerOfHanoi(n-1, sourcePeg, auxiliaryPeg, targetPeg);
    // Move the nth disk from the source peg to the target peg
    console.log("Move disk " + n + " from peg " + sourcePeg + " to peg " + targetPeg);
    // Move the n-1 disks from the auxiliary peg to the target peg using the source peg
    towerOfHanoi(n-1, auxiliaryPeg, targetPeg, sourcePeg);
}

// Example use of the function
towerOfHanoi(3, 'A', 'C', 'B');

Output:

Move disk 1 from peg A to peg C
Move disk 2 from peg A to peg B
Move disk 1 from peg C to peg B
Move disk 3 from peg A to peg C
Move disk 1 from peg B to peg A
Move disk 2 from peg B to peg C
Move disk 1 from peg A to peg C

4. Step By Step Explanation

1. The problem is tackled using recursion.

2. If there's only one disk, simply move it.

3. Otherwise, we first move the top n-1 disks to the auxiliary peg, then move the nth disk to the target peg, and finally, we move the n-1 disks from the auxiliary peg to the target peg.

Comments