Skip to content

Instantly share code, notes, and snippets.

@onacit
Last active November 9, 2019 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onacit/26c00e97c71e6a95f7be7136d2b11e06 to your computer and use it in GitHub Desktop.
Save onacit/26c00e97c71e6a95f7be7136d2b11e06 to your computer and use it in GitHub Desktop.
Run Monty Hall Problem with Random
import java.security.*;
import java.util.*;
import java.util.concurrent.atomic.*;
public class MontyHallProblem {
//private static final long COUNT = 1048576L;
private static final long COUNT = 30000L;
static { assert COUNT > 0L; }
private static final int DOORS = 3;
static { assert DOORS > 0; }
public static void main(final String... args) throws Exception {
final LongAdder adder = new LongAdder();
final SecureRandom random = SecureRandom.getInstanceStrong();
final List<Boolean> doors = new ArrayList<Boolean>(DOORS);
for (long i = 0L; i < COUNT; i++) {
assert doors.isEmpty();
{
boolean car = false;
for (int j = 0; j < DOORS; j++) {
if (car) {
doors.add(Boolean.FALSE);
continue;
}
doors.add(random.nextBoolean());
car = doors.get(doors.size() - 1);
}
if (!car) {
final int k = random.nextInt(DOORS);
doors.remove(k);
doors.add(k, Boolean.TRUE);
}
}
final boolean one = doors.remove(random.nextInt(doors.size()));
if (one) { // car -> fail, cuz we gonna change anyway.
doors.clear();
continue;
}
// remove one of those for goats
for (final Iterator<Boolean> j = doors.iterator(); j.hasNext(); ) {
final boolean car = j.next();
if (!car) { // goat
j.remove();
break;
}
}
// always change
if (doors.remove(0)) { // and it's for the car?
adder.add(1L); // success
}
}
System.out.println(adder.doubleValue() / COUNT);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment