Skip to content

Instantly share code, notes, and snippets.

@halilbilgin
Created October 21, 2017 18:57
Show Gist options
  • Save halilbilgin/0f5c5d675fb0f670295bdea7f15ff8b9 to your computer and use it in GitHub Desktop.
Save halilbilgin/0f5c5d675fb0f670295bdea7f15ff8b9 to your computer and use it in GitHub Desktop.
Solve Monty Hall Problem using Monte Carlo simulations
public class MontyHall {
int usersChoice;
int doorWithTheCar;
}
import java.io.ObjectInputStream.GetField;
import java.util.Random;
public class MontyHallMonteCarlo {
public MontyHall GetRandomScenario() {
Random random = new Random();
MontyHall game = new MontyHall();
game.usersChoice = random.nextInt(3) + 1;
game.doorWithTheCar = random.nextInt(3) + 1;
return game;
}
public float SimulateWinSwitch(int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
int indicator = 0;
MontyHall game = this.GetRandomScenario();
if(game.doorWithTheCar != game.usersChoice){
indicator = 1;
}
sum += indicator;
}
// By strong law of large numbers:
return (float)sum / n;
}
public static void main(String[] args) {
MontyHallMonteCarlo trial = new MontyHallMonteCarlo();
System.out.println(trial.SimulateWinSwitch(10000));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment