I have been facing considerable difficulty in comprehending the functioning of this program. Despite reading numerous articles, none of them provide a clear explanation of how the program operates. I will make an effort to articulate my questions as clearly as possible.
Therefore, my inquiry is regarding the operational mechanisms of this program.
// Java recursive program to solve tower of hanoi puzzle
class GFG
{
// Java recursive function to solve tower of hanoi puzzle
static void towerOfHanoi( int n, char from_rod, char to_rod, char aux_rod)
{
if (n == 1 )
{
System.out.println( "Move disk 1 from rod " + from_rod + " to rod " + to_rod);
return;
}
towerOfHanoi(n- 1 , from_rod, aux_rod, to_rod);
System.out.println("Move disk "+ n + " from rod " + from_rod + " to rod " + to_rod);
towerOfHanoi(n- 1 , aux_rod, to_rod, from_rod);
}
// Driver method
public static void main(String args[])
{
int n = 4 ; // Number of disks
towerOfHanoi(n, 'A' , 'C' , 'B' ); // A, B and C are names of rods
}
}
Extracted from an online article on exit interview questions resource.
I have a grasp on the initial call and the subsequent calls that occur after the return statement. However, what perplexes me is how this program is not encountering any errors. It almost appears like magic to me.
In the second call to the method, the arguments are presented in a different order compared to the method's definition. The method's definition states that the arguments are FROM, TO, and AUX, but the second call indicates FROM, AUX, and TOO.
Does this order of arguments affect the result, or is it irrelevant?
Additionally, there comes a point where the value of 'n' needs to revert to its original value; otherwise, the program would only be capable of moving a single disk. I am unable to locate any increment operation in the code. When I run the program through a debugger in my IDE with 3 disks, the value of 'n' sometimes transitions from 1 to 3, and I cannot comprehend how this occurs.
This problem is incredibly confusing, and I feel exhausted from reading articles that do not provide a comprehensive walkthrough of the code solution.