konstantin
konstantin

Reputation: 893

Function method in java

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 number as a number of a nth dice rolling outcome. My code is the following:

public static double f(int sum, int r) {

if (r== 0) { 
  if (pr(s) ){ 
      return 1; 
  }
  else 
    return 0; 
}

double rsum = 0; 

for (int i = 1; i <= 6; i++) { 
  rsum += f(sum + i, r- 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.

EDIT: in the debugging that it goes like that: f3(1,2) -> f(2,1) and then instead of f(3,0) it goes again to ev3(2,1) any idea why this is happening?

Upvotes: 1

Views: 148

Answers (2)

Dimitar Dimitrov
Dimitar Dimitrov

Reputation: 16357

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
  • 62 times for all the possible results from the second dice roll (6 times for each of the possible results from the first dice roll)
  • ...
  • 6n 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.

Upvotes: 1

ArcSine
ArcSine

Reputation: 644

It seems the function's purpose is to average 6 different rolls of (1,2,3,4,5,6). It does this rollsLeft times, until it reaches the bottom. Basically if the sum for all the rolls is 3,5,6,11,13 or 17, then a value of 100 is provided, otherwise subtract 50 from the overall return value.

The recursion seems to be looking for the probability given all possible rolls.

Really, for sum=0 and rollsLeft=n the value is static meaning you could precompute this by hand, versus computing it at runtime.

Upvotes: 2

Related Questions