-1

我正在尝试制作一个代表生日悖论的程序。我理解这个悖论,我很确定我的代码是错误的,但我不确定我哪里出错了。我浏览了相关的帖子,但没有发现任何有用的东西。我小时候写的代码,如果有点乱,请见谅。我知道还有其他方法可以做到这一点,并且我理解为什么这些方法有效。我只想知道为什么我的代码不起作用。谢谢!

编辑:对不起,来晚了。忘了说我的实际问题是什么。我按原样运行,预计会得到大约 50.5%,这是理论值。但是,相反,我得到了大约 21.1%。

public class Main {
    static int trialsSucceeded = 0; // Stores number of successful trials
    static final int TRIALS = 1000000; // 1,000,000 is a good number :) Biggest I've tried: 2,147,483,647, which is Integer.MAX_VALUE
    static int numberOfPeople = 23; // The 'n' value for the birthday paradox

public static void main(String[] args) {
    ArrayList<Integer> birthdays = new ArrayList<Integer>(); // Stores people's birthdays

    // Runs until desired trials are completed
    for (int trialNumber = 0; trialNumber < TRIALS; trialNumber++) {
        // Provides progress updates to user
        if (trialNumber % 1000 == 0)
            System.out.printf("%.1f%% complete\n", (double) trialNumber * 100 / TRIALS);

        // Populates the birthdays array
        for (int personNumber = 0; personNumber < numberOfPeople; personNumber++) {
            birthdays.add(getRandInt(1, 365));
        }

        // Used later to see if current trial should end
        int prevTrialsSucceeded = trialsSucceeded;

        // Checks each person's birthday against everyone else's
        for (int i = 0; i < birthdays.size(); i++) {
            for (int j = i + 1; j < birthdays.size(); j++) {
                // If birthdays match, marks trial as a success jumps to next trail
                if ((birthdays.get(i) == birthdays.get(j))) {
                    trialsSucceeded += 1;
                    break;
                }
            }
            // Jumps to next trial if this one has already succeeded
            if (prevTrialsSucceeded != trialsSucceeded) {
                break;
            }
        }
        // Clears list of birthdays to get ready for next trial
        birthdays.clear();
    }
    // Tells user ratio of successful trials to total trials
    System.out.println(((double) trialsSucceeded / TRIALS * 100) + "% of trials succeeded");
}

private static int getRandInt(int lowerBound, int upperBound) {
    // Returns random integer between lowerBound and upperBound
    Random random = new Random();
    return random.nextInt(upperBound - lowerBound + 1) + lowerBound;
}

}

4

2 回答 2

2

根本问题是这一行:

if ((birthdays.get(i) == birthdays.get(j))) {

这是比较Integer对象的身份相等性。您需要在这里做的是比较价值平等:

if ((birthdays.get(i).equals(birthdays.get(j)))) {

这应该会给你正确的结果,略高于 50%。

于 2017-01-11T04:32:21.217 回答
1

正如其他人正确理解的那样,您的问题根源于比较参考文献......但即使在解决该问题时,这里的解决方案既不高效也不容易掌握。

有一种更简单的检查方法:只需使用 Set 来存储随机数生日而不是列表。但在添加下一个数字之前,您使用 Set.contains() 检查该数字是否已经在集合中。如果是这样,您找到了匹配项……您可以在此处停下来!

于 2017-01-11T04:25:04.137 回答