Created
October 15, 2016 11:55
-
-
Save flyfy1/3549e41ba182aaad916a9cbf44871f88 to your computer and use it in GitHub Desktop.
Java Simulation for the MontyHall Problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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