JavaScript - Tower of Hanoi Program

The Tower of Hanoi is a classic puzzle that exemplifies recursion in programming. The topic is straightforward but thought-provoking, making it an excellent choice for teaching algorithmic thinking and recursive solutions. In this blog post, we will look at the Tower of Hanoi problem and how to solve it using JavaScript.

function tower_Of_Hanoi(n, source_Rod, target_Rod, auxiliary_Rod) {

    if (n === 1) {

        console.log(`Move disk 1 from ${source_Rod} to ${target_Rod}`);

        return;

    }

    // Move n-1 disks from source to auxiliary

    tower_Of_Hanoi(n - 1, source_Rod, auxiliary_Rod, target_Rod);    

    // Move the nth disk from source to target

    console.log(`Move disk ${n} from ${source_Rod} to ${target_Rod}`);  

    // Move the n-1 disks from auxiliary to target

    tower_Of_Hanoi(n - 1, auxiliary_Rod, target_Rod, source_Rod);

}

// Example: Solve the problem for 3 disks

const num_Of_Disks = 3;

tower_Of_Hanoi(num_Of_Disks, 'A', 'C', 'B');

 

Explanation of the Code

Base Case: If there is only one disk (n === 1), we can transfer it directly from the source rod to the target rod.

Recursive Case:

We transfer n-1 disks from the source rod to the auxiliary rod, utilizing the target rod as a temporary holding point.

Then we move the nth disk from the source rod to the destination rod.

Finally, we transfer the n-1 disks from the auxiliary rod to the target rod, using the source rod as a temporary resting point.