konstantin - 1 year ago 84

Java Question

I am trying to understand a block of code i have how exactly it works. My code is an example of recursion and try to calculate the chance of a prime number as a number of a nth dice rolling outcome. My code is the following:

`public static double ev3(int sum, int rollsLeft) {`

if (rollsLeft == 0) {

if (sum == 3 ){

return 1;

}

else

return 0;

}

double rsum = 0;

for (int i = 1; i <= 6; i++) {

rsum += ev3(sum + i, rollsLeft - 1)/6.0;

}

return rsum;

}

I struggle to understand how the recursion exactly is working and if I am doing what I am suppose to. Why sum takes values beyond six.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Your function iterates over all possible permutations for some number of dice rolls and provides some metric for them. It's called recursively multiple times:

- once initially (not recursively)
- 6 times for all the possible results from the first dice roll
- 6
^{2}times for all the possible results from the second dice roll (6 times for each of the possible results from the first dice roll) - ...
- 6
^{n}times for all the possible results from the n-th dice roll

Your function evaluates some custom metric, but if you replace 100 with 1, -50 with 0, and generalize the `sum == 3 || sum == 5 || sum == 7 || sum == 11 || sum == 13 || sum == 17`

expression to an `isPrime(sum)`

function, you'll be able to calculate the probability of the sum of n dice rolls being a prime number.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**