I am trying to generate 20 random booleans and see if they have the same value i.e. either all true or all false. I expected the program to run for a while as the probability should be 1/(2^20) *100 * 2, which is something like 0.00019%.
However, I run my program (shown below) and it terminated extremely quickly, sometimes even take 1 loop. Is there something wrong in my program, or with my logic?
BigInteger bi = BigInteger.ZERO;
Random rand = new Random();
while (true) {
bi = bi.add(BigInteger.ONE);
System.out.println(bi);
boolean x = rand.nextBoolean();
if (x == rand.nextBoolean()
== rand.nextBoolean() == rand.nextBoolean()
== rand.nextBoolean() == rand.nextBoolean()
== rand.nextBoolean() == rand.nextBoolean()
== rand.nextBoolean() == rand.nextBoolean()
== rand.nextBoolean() == rand.nextBoolean()
== rand.nextBoolean() == rand.nextBoolean()
== rand.nextBoolean() == rand.nextBoolean()
== rand.nextBoolean() == rand.nextBoolean()
== rand.nextBoolean() == rand.nextBoolean()
) {
System.out.print(x);
return;
}
}
Aucun commentaire:
Enregistrer un commentaire