In: Computer Science
In Java please
Consider the following problem: There are three pegs, denoted A, B, and C, and N disks of different sizes. Originally, all the disks are on peg A, stacked in decreasing size from bottom to top. Your goal is to transfer all the disks to peg B, and the rules are that you can only move one disk at a time, no disk can be moved onto a smaller one, and you make use of all pegs.
Develop a solution to this problem based on the principle of recursion, i.e., this problem has to be solved by programming a recursive procedure. The use of global variables is not permitted. Your solution must print a protocol about the movements of the disks. Use only pseudocode to write down your solution.
Pseudocode :
//recursive function to solve a problem
static void solution(int n, char from_peg, char to_peg, char
aux_peg)
{
if (n == 1)
{
System.out.println("Move disk 1 from peg " + from_peg + " to peg "
+ to_peg);
return;
}
solution(n-1, from_peg, aux_peg, to_peg);
System.out.println("Move disk " + n + " from peg " + from_peg + "
to peg " + to_peg);
solution(n-1, aux_peg, to_peg, from_peg);
}
Approach :
Remove all N-1 disks to other pegs as per requirement and then set N number disk to peg B and again perform same process for N-1 disks.
Java Code is as below :
import java.util.*;
public class Main
{
//recursive function to solve a problem
static void solution(int n, char from_peg, char to_peg, char aux_peg)
{
if (n == 1)
{
System.out.println("Move disk 1 from peg " + from_peg + " to peg " + to_peg);
return;
}
solution(n-1, from_peg, aux_peg, to_peg);
System.out.println("Move disk " + n + " from peg " + from_peg + " to peg " + to_peg);
solution(n-1, aux_peg, to_peg, from_peg);
}
public static void main(String args[])
{
//number of disks
int N = 3;
// A, B and C are names of pegs
solution(N, 'A', 'B', 'C');
}
}
Please refer to the screenshot of the code to understand the indentation of the code.
output is also attached in the above screenshot for 3 disks.