java - 动态变化的嵌套 for 循环数量

标签 java

我正在学习 Java - 遇到了这个问题:

Write a program that rolls n dice, where the dice are all d-sided. By using simulation, report an approximate value for the probability of rolling a total of x or more, using the dice, where x, n and d are all given as inputs. For example, if n = 2, d = 6 and x = 7, the program should report 58.3% probability (approximately).

这是我想出来的

public class Main {

    public double calcProbability(int n, int d, int x){
        int[] sums = new int[(int)Math.pow(d, n)]; //Creates an array of max size needed
        int counter = 0;    
        int occurrences = 0; //No. of times that the number being added to the array is greater than d
        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); //Returning probability
    }

    public static void main(String[] args) {
        System.out.println(new Main().calcProbability(2, 6, 7));
    }

}

它适用于 n=2(我认为),因为我使用了两个嵌套的 for 循环。但是我无法弄清楚如何使用 n 来改变 for 循环的数量(这将允许我将所有可能的总数添加到数组中——其余代码应该可以正常工作)。

希望得到一些指导。


谢谢大家,考虑到大家的贡献,修改后的方法如下:

public double calcProbability(int n, int d, int x){
        Random random = new Random(); //Random numbers simulate dice rolling
        int occurrences = 0; //No. of times that the number is greater than d
        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; //Will be an approximation
    }

存储这些数字然后计算出现的次数是没有意义的 - 而只是计算它发生的次数并继续前进。

最佳答案

以动态循环为目的,答案如下。但是,请跳至第二段以获得更推荐的执行此操作的方法。获得动态循环的方法是递归。如果你愿意,我可以详细说明,但在高层次上,你拥有的是一个参数,它指定第 n 个骰子和减量,当它到达第 0 个骰子时,递归结束。您必须对变量进行相当多的更改,并将它们移动到参数或全局变量中,以便您可以使用函数不断更新它们。

对于这个问题,我会采用完全不同的方法。创建一个名为 Roll 的函数,它接受两个参数:骰子值的范围和要掷的骰子数量。我会将 的功能的细节留给您,但它涉及生成一定次数的随机数。由于该问题需要模拟,因此多次调用此 Roll 函数,然后使用一个数组来跟踪得出的答案。届时,进行除法和百分比以获得良好的近似值。

关于java - 动态变化的嵌套 for 循环数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34515665/

相关文章:

java - tomcat应用程序未启动的maven项目错误

java - Android:按钮向南

java - Tika 在服务器模式下的性能

java - 连接 BassBoost 时 MediaPlayer 不播放 - 错误 (-22, 0)

java - 将 CSV 文件导入二维字符串数组

java - SpringBoot 2.1.3 : Embedded Tomcat Logging

java - Jogl-2.0不支持GLAutoDrawable gLDrawable.addKeyListener(this); ?

java - Java 中 String.length() 的时间复杂度是多少?

java - 向数组添加数据时如何删除括号

java - Java中的深度优先搜索