user1042244
user1042244

Reputation:

need some explanation about recursion?

I still have problem to understand the ancient problem the tower of Hanoi recursion how it really works here. i have read it theoretically but i still don't get how recursion is being called here. Can anybody explain each step what is going on for ex if the value of ring is 2.

In general i know that recursion it calls itself but here i get stuck:

public static void main(String[] args) {
// TODO Auto-generated method stub
    Scanner s = new Scanner(System.in);
    System.out.println("Input the number of rings");
    int rings = s.nextInt();
    move(rings, 'A', 'B', 'C');
}

public static void move(int rings, char x, char y, char z){
    if(rings > 0){
        move(rings - 1, x, z, y);
        System.out.println("Move ring " + rings + " from peg " + x + " to " + y + ".");
        move(rings - 1, z, y, x);   
    }
}

why when i give to ring value 1 it goes directly to this line:

System.out.println("Move ring " + rings + " from peg " + x + " to " + y + "."); 

Thank you.

Upvotes: 1

Views: 134

Answers (1)

cangrejo
cangrejo

Reputation: 2202

When the value of rings is 1, what happens is the following:

-move method is called with rings = 1
-the condition is met (because 1 > 0 is true) so move is called with rings = 0
-another instance of the move method starts, but this time rings = rings - 1 = 0
-the condition is not met (because 0 > 0 is false) so nothing happens and that method ends
-we're back at the first instance of the method. Now, the System call is executed
-after that, move is called again, with rings = rings - 1 = 0
-another instance of the method starts, and again the condition is not met (0 > 0 is false), so the method is terminated without entering the "if" block

The same will happen if rings equals 2, but a larger and more complex recursive tree will take place. The move method in which rings is 2 will call 2 move methods where rings equals 1, which will themselves call 2 move methods each in which rings is 0.

     2
    / \
  1     1
 / \   / \
0   0 0   0

Step by step, with rings = 2, this would happen:
-move(1, x, z, y);
-move(0, x, z, y);
-System.out.println("Move ring 1 from peg A to C.");
-move(0, z, y, x);
-System.out.println("Move ring 2 from peg A to B.");
-move(1, z, y, x);
-move(0, x, z, y);
-System.out.println("Move ring 1 from peg C to B.");
-move(0, z, y, x);

The value of rings in each call gives you a hint of where it's happening. For example,
move(1, x, z, y); happens in the method in which rings = 2, because the call is move(rings-1, x, z, y).

I hope this helps.

Upvotes: 2

Related Questions