101 Logo
onenoughtone

Code Implementation

Tower of Hanoi Puzzle Solver Implementation

Below is the implementation of the tower of hanoi puzzle solver:

solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
function towerOfHanoi(n, source, auxiliary, target) {
// Base case: only one disk to move
if (n === 1) {
console.log(`Move disk 1 from ${source} to ${target}`);
return;
}
// Step 1: Move n-1 disks from source to auxiliary
towerOfHanoi(n - 1, source, target, auxiliary);
// Step 2: Move the largest disk from source to target
console.log(`Move disk ${n} from ${source} to ${target}`);
// Step 3: Move n-1 disks from auxiliary to target
towerOfHanoi(n - 1, auxiliary, source, target);
}
// Test cases
console.log("Tower of Hanoi with 1 disk:");
towerOfHanoi(1, 'A', 'B', 'C');
// Output: Move disk 1 from A to C
console.log("\nTower of Hanoi with 2 disks:");
towerOfHanoi(2, 'A', 'B', 'C');
// Output:
// Move disk 1 from A to B
// Move disk 2 from A to C
// Move disk 1 from B to C
console.log("\nTower of Hanoi with 3 disks:");
towerOfHanoi(3, 'A', 'B', 'C');
// Output:
// Move disk 1 from A to C
// Move disk 2 from A to B
// Move disk 1 from C to B
// Move disk 3 from A to C
// Move disk 1 from B to A
// Move disk 2 from B to C
// Move disk 1 from A to C
// Calculate the number of moves for n disks
function calculateMoves(n) {
return Math.pow(2, n) - 1;
}
console.log("\nNumber of moves required:");
for (let i = 1; i <= 5; i++) {
console.log(`For ${i} disk(s): ${calculateMoves(i)} moves`);
}

Step-by-Step Explanation

Let's break down the implementation:

  1. Understand the Problem: The Tower of Hanoi puzzle involves moving a stack of disks from one rod to another, following specific rules about disk movement.
  2. Identify the Recursive Structure: Recognize that moving n disks can be broken down into moving n-1 disks, then moving the largest disk, then moving n-1 disks again.
  3. Define the Base Case: The simplest case is moving a single disk directly from the source to the target rod.
  4. Implement the Recursive Solution: Write a function that handles the base case and implements the three-step recursive approach for the general case.
  5. Analyze the Solution: Understand that the number of moves required is 2^n - 1, which grows exponentially with the number of disks.
ProblemSolutionCode
101 Logo
onenoughtone