免责声明:我不想要这个问题的答案。我只是需要一些指导。
我想使用HashSet
.
现在,当我运行它时,collisionCount
它比我预期的要低得多。首先,我预计collisionCount
一组 10 人的 11446(或 0.11446 的概率)。然后当我达到 100 人时,我预计碰撞计数为 100,000(概率为 1.0)。但是,对于每 10 人,collisionCount 仅按 1 计数(10 人:1 次碰撞,20 人:2 次碰撞,30 人:3 次碰撞,等等)。
这是我到目前为止写的代码:
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class BirthdayParadox
{
public static void main(String [] args)
{
Random rand = new Random();
int tests = 100000;
int collisionCount = 0;
for(int people = 10; people <= 100; people += 10)
{
Set<Integer> birthdays = new HashSet<>(365);
birthdays.add(rand.nextInt(365));
for(int runs = 0; runs < tests; runs++)
{
int randomBirthday = rand.nextInt(365);
if(birthdays.contains(randomBirthday))
{
collisionCount++;
break;
}
birthdays.add(randomBirthday);
}
float prob = (float)collisionCount / tests;
System.out.println("After " + tests + " tests there were " +
collisionCount + " occurrences of shared " +
" birthdays in a set of " + people + " people.");
System.out.println("Probability : " + prob);
}
}
}
我想我的问题是:我是否在我的任何一个 for 循环中都没有做正确的事情才能collisionCount
正确计数?
我是学习 Java 的新手,也是 Stack Overflow 社区的新手,并且仍在学习中。非常感谢任何帮助/建议/提示。