我正在尝试制作一个代表生日悖论的程序。我理解这个悖论,我很确定我的代码是错误的,但我不确定我哪里出错了。我浏览了相关的帖子,但没有发现任何有用的东西。我小时候写的代码,如果有点乱,请见谅。我知道还有其他方法可以做到这一点,并且我理解为什么这些方法有效。我只想知道为什么我的代码不起作用。谢谢!
编辑:对不起,来晚了。忘了说我的实际问题是什么。我按原样运行,预计会得到大约 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;
}
}