Skip to content

Instantly share code, notes, and snippets.

@OutOfBrain
Created January 29, 2017 01:16
Show Gist options
  • Save OutOfBrain/f633f97231fb3217f9a55e9d3ffa0f01 to your computer and use it in GitHub Desktop.
Save OutOfBrain/f633f97231fb3217f9a55e9d3ffa0f01 to your computer and use it in GitHub Desktop.
Monty Hall Problem Simulation
import java.util.Random;
public class MontyHallSimulation {
public static void main(String[] args) {
new MontyHallSimulation().start();
}
private Random rand = new Random(4);
private void start() {
int winstrat1 = 0;
int winstrat2 = 0;
for (int i = 0; i < 1e6; ++i) {
if (strat1()) {
++winstrat1;
}
if (strat2()) {
++winstrat2;
}
}
System.out.println(winstrat1);
System.out.println(winstrat2);
}
/**
* Don't change choice when offered, stick with initial choice.
*/
private boolean strat1() {
return rand.nextInt(3) == rand.nextInt(3);
}
/**
* Switch after offered a choice and one loser revealed.
*/
private boolean strat2() {
// prepare starting condition
int win = rand.nextInt(3);
int choice = rand.nextInt(3);
int lose1;
int lose2;
// figure out loses
switch (win) {
case 0:
lose1 = 1;
lose2 = 2;
break;
case 1:
lose1 = 0;
lose2 = 2;
break;
case 2:
lose1 = 0;
lose2 = 1;
break;
default:
throw new RuntimeException("no");
}
// whenever the loser was chosen in the first stage
// the swap in the second stage makes it a winner
return lose1 == choice || choice == lose2;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment