The recursive function operates on each node, which calls the recursive function on all it's children, i.e:
The analogy you presented, the child can have more children, kind of confuses me. If I am using recursion, I am making another call to the method I am in, so does that not mean that I am simply going back and forth between 2 children?...snip...
if wewhich allows you to operate on an indeterminable number of children.void Func(Node N){ for(int i=0;i<N.Children.Count;i++) Func(N.Children); return; }
Made a small change for doing unnecessary work.>>>
package mainPackage; public class RecursionCoin { final static int toonie = 6; static int[] coin = {0,0,0,0}; static int turns = 0; public static void main(String[] args) { for(int i = 0; i < 4; i++){ coin = 0 + (int)(Math.random() * ((6 - 0) + 1)); } checkCoins(coin, turns); System.out.println(turns); } private static void checkCoins(int[] coin, int turns2) { turns = turns2 + 1; for(int i = 0; i < 4; i++){ if(coin != toonie){ coin = 0 + (int)(Math.random() * ((6 - 0) + 1)); return checkCoins(coin, turns); //Once this function returns succesfully, you know that you are done. //returning here allows all your recursive functions to escape, instead of each doing potentially more work. } } } }
That code has a side effect. You're returning a void method? What is the point of that. What you should do is say that once it returns successfully, you break out of the loop:
checkCoins:
for(int i = 0; i < 4; i++) {
if(coin != toonie) {
coin = (int) (Math.random() * ((6-0) + 1));
return checkCoins(coin, turns);
break checkCoins;
}
}
This is a labeled break statment.
Once it returns successfully, you break out and avoid a side-effect of the method.
(Yes, I know it's an unimportant side effect that doesn't actually affect anything, however consistency !)
(I just want to point out that there are some non-elegant pieces of your code, such as using an int assigned to a random number to toonie. You could create a class with an state called isToonie
class Coin {
bool isToonie = false;
}
and then have your code make more sense (instead of: if (coin != toonie), we get: if (coins[index].isToonie))).
Cheers !