繁体   English   中英

如何多次运行while循环

[英]how to run a while loop several time

我想解决这个任务,但我不能运行 while 循环超过 1 次。

在这个任务中,你将解决我们所说的生日问题。 假设我们有一个空教室。 学生们一一走进教室。 我们假设每个学生的生日在 0 到 365 之间,其中 0 代表 1 月 1 日,364 代表去年 12 月。 问题在于找出必须进入教室的学生人数的平均值,以便两个学生在同一天过生日。 提示:运行大量模拟。 对于每个模拟,使用一个数组来比较学生的随机生日。

public class Main {


    public static void main(String[] args) {
        int count;
        boolean[] used;

        used = new boolean[365];

        count = 0;

        while (true) {
            int birthday;  // The selected birthday.
            birthday = (int) (Math.random() * 365);
            count++;
            if (used[birthday]) {
                // This day was found before; It's a duplicate.
                break; }

            used[birthday] = true; }
        System.out.println("A duplicate birthday was found after "
                + count + " kids came to the class.");


      //  double[] arr = {Numbers};
       // double total = 0;

        //for(int i=0; i<arr.length; i++){
           // total = total + arr[i];
        //}



        //double average = total / arr.length;


       // System.out.format("The average is: %", average);

    }

只需在 for 循环中围绕分配和计数,即可获得模拟次数。

for (int 模拟 = 0; 模拟 < 100000; 模拟++) {...... }

在 while 循环每次中断后,将计数添加到另一个变量。 完成所有模拟后,将计数除以模拟次数以获得平均“生日问题”概率。

您可以在模拟周围使用for 循环

我建议将模拟代码放入单独的方法中以使事情更清楚。 这是一个完整的例子:

public static void main(String[] args) throws Exception {
    int runs = 100000;
    long studentsNeeded = 0;
    for (int i = 0; i < runs; i++) {
        studentsNeeded += studentsNeededBeforeWeFoundASharedBirthday();
    }
    double meanStudentsNeeded = (double) studentsNeeded / runs;
    System.out.println(String.format("After %d runs, it took %.2f students on "
            + "average before we found a shared birthday.", runs, meanStudentsNeeded));
}

private static int studentsNeededBeforeWeFoundASharedBirthday() {
    Random r = new Random();
    boolean[] used = new boolean[365];
    int count = 0;
    while (true) {
        count++;
        int birthday = r.nextInt(365);
        if (used[birthday]) {
            break;
        }
        used[birthday] = true;
    }
    return count;
}

印刷:

在运行 100000 次后,我们平均需要 24.61 名学生才能找到共享生日。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM