Skip to content

Instantly share code, notes, and snippets.

@novoj
Created December 10, 2012 09:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save novoj/4249532 to your computer and use it in GitHub Desktop.
Save novoj/4249532 to your computer and use it in GitHub Desktop.
Monte Carlo test for testing different strategies for guessing game. You have three doors and only one is winning one. You make your choice, and then moderator opens some other door showing you that this doors don't win. He then offers you to change your guess. Will you have bigger chance to win when you change your mind or not?
import java.util.Random;
public class MonteCarlo {
private enum Choice {
WINNING, LOSING
}
private static int ITERATIONS = 1000000;
private static final Random randomGenerator = new Random();
private static GuessStrategy stayStrategy = new StayStrategy();
private static GuessStrategy changeStrategy = new ChangeStrategy();
public static void main(String[] args) {
for (int i = 0; i < ITERATIONS; i++) {
Choice[] wins = generateRandomChoices();
int firstChoice = randomGenerator.nextInt(3);
int excludedFalseChoice = -1;
do {
excludedFalseChoice = randomGenerator.nextInt(3);
} while (excludedFalseChoice == firstChoice || wins[excludedFalseChoice] == Choice.WINNING);
stayStrategy.guess(wins, firstChoice, excludedFalseChoice);
changeStrategy.guess(wins, firstChoice, excludedFalseChoice);
}
System.out.println("Stay strategy success: " + (float) stayStrategy.successes / (float) ITERATIONS * 100 + "%");
System.out.println("Change strategy success: " + (float) changeStrategy.successes / (float) ITERATIONS * 100 + "%");
}
private static Choice[] generateRandomChoices() {
Choice[] wins = new Choice[3];
for (int j = 0; j < wins.length; j++) {
wins[j] = Choice.LOSING;
}
wins[randomGenerator.nextInt(3)] = Choice.WINNING;
return wins;
}
private abstract static class GuessStrategy {
protected int successes = 0;
protected int losses = 0;
public int getSuccesses() {
return successes;
}
public int getLosses() {
return losses;
}
public abstract void guess(Choice[] wins, int firstChoice, int excludedChoice);
}
private static class ChangeStrategy extends GuessStrategy {
@Override
public void guess(Choice[] wins, int firstChoice, int excludedChoice) {
for (int i = 0; i < wins.length; i++) {
if (i != firstChoice && i != excludedChoice) {
if (wins[i] == Choice.WINNING) {
this.successes++;
} else {
this.losses++;
}
}
}
}
}
private static class StayStrategy extends GuessStrategy {
@Override
public void guess(Choice[] wins, int firstChoice, int excludedChoice) {
if (wins[firstChoice] == Choice.WINNING) {
this.successes++;
} else {
this.losses++;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment