I am learning Java - ran into this problem:
Write a program in which a roll of n cubes, where the bones are all d-sided. From using a simulation, report an approximate probability value that rolls all x or more, using dice, where x, n and d are all data as input. For example, if n = 2, d = 6, and x = 7, the program should report a probability of 58.3% (approximately).
Here is what I came up with
public class Main {
public double calcProbability(int n, int d, int x){
int[] sums = new int[(int)Math.pow(d, n)];
int counter = 0;
int occurrences = 0;
for(int i=1;i<=d;i++){
for(int j=1;j<=d;j++){
if((i+j)>=x){
occurrences++;
}
sums[counter]=(i+j);
counter++;
}
}
return (double)occurrences/Math.pow(d, n);
}
public static void main(String[] args) {
System.out.println(new Main().calcProbability(2, 6, 7));
}
}
It works fine for n = 2 (I think), since I use two nested loops. But it’s hard for me to understand how to change the number of loops with n (this will allow me to add all the possible totals to the array - the rest of the code should work fine, as it is).
Would thank for some recommendations.
Thanks to everyone, after considering each contribution, here is the revised method:
public double calcProbability(int n, int d, int x){
Random random = new Random();
int occurrences = 0;
for(int i=0;i<100000;i++)
{
int sum = 0;
for(int j=0;j<n;j++)
{
sum+=random.nextInt(d)+1;
}
if(sum>=x) {
occurrences++;
}
}
return (double)occurrences/100000;
}
, , , .