Skip to content

Instantly share code, notes, and snippets.

@flyfy1
Created October 15, 2016 11:55
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 flyfy1/3549e41ba182aaad916a9cbf44871f88 to your computer and use it in GitHub Desktop.
Save flyfy1/3549e41ba182aaad916a9cbf44871f88 to your computer and use it in GitHub Desktop.
Java Simulation for the MontyHall Problem
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
public class MontyHall {
static Random rand = new Random();
public static void main(String args[]){
int no_switch_correct = 0,
total_count = 0,
switch_correct = 0;
// without switch
for(int i = 0 ; i < 100000; i++){
total_count++;
int answer = rand.nextInt(3);
int guess = rand.nextInt(3);
if(answer == guess){
no_switch_correct++;
}
int new_guess = guessAfterSwitch(answer, guess);
if(answer == new_guess){
switch_correct++;
}
}
System.out.printf("No switch ratio: %.2f\n", ((double) no_switch_correct) / total_count);
System.out.printf("With switch ratio: %.2f\n", ((double) switch_correct) / total_count);
}
public static int guessAfterSwitch(int ans, int guess){
if(ans == guess){
int res = rand.nextInt(2);
if(res == ans) {
res++;
}
return res;
} else{
return ans;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment