Monty Hall Problem Simulation

I'm trying to write a main method that proves the Monty Hall scenario with a for loop. The Monty Hall problem is based off of a probability riddle. You are playing a game where there are 3 closed doors, behind one is a car but behind the other two are goats. After you pick a door, the game host shows you one of the other doors that has a goat in it. He then asks if you want to change your guess. So say you first guess door 1, the host then opens door 3 to show you a goat so he asks if you want to switch your answer to door 2. Probability tells us that if you switch there is a 2/3 chance that you will win the car (not 1/2 like most people think at first). The object of my method is to prove this by using a for loop and running it a large number of times ( i used 1000000) to prove the percent of winning when switching is 66.7%. The problem is when I run my code I keep getting 50% as my output and I cannot see why.

Code Java:

import java.util.Random;
public class MontySim {
public static void main(String[] args) {
Random ran = new Random();
int n = 1000000;
int wins = 0;
for (int i = 0; i < n; i++) {
int winningNumber = ran.nextInt(3) + 1;
int losingNumber = ran.nextInt(3) + 1;
while (losingNumber == winningNumber) {
losingNumber = ran.nextInt(3) + 1;
}
int firstSelection = ran.nextInt(3) + 1;
while ((firstSelection == losingNumber)) {
firstSelection = ran.nextInt(3) + 1;
}
int secondSelection = ran.nextInt(3) + 1;
while ((secondSelection == firstSelection)
|| (secondSelection == losingNumber)) {
secondSelection = ran.nextInt(3) + 1;
}
if (secondSelection == winningNumber) {
wins ++;
}
}
double percent = 100 * wins / n;
System.out.print(percent + "%");
}
}

Any thoughts on why I'm not getting 66.7%? I thought i set it up well. I have the random generator making 4 numbers, the door where the car is (winningNumber), the door the host shows you (losingNumber), the door your choose first (firstSelection) and the door you switch to (secondSelection). I also made while statements to make sure the that the value of losingNumber cannot be the same as winningNumber, as well as making sure the firstSelection cannot be the same as the losingNumber, as well as making sure the secondSelection cannot be the same as firstSelection or the losingNumber.

Thanks

Casey

Re: Monty Hall Problem Simulation

The problem is in the order you've done things (thus altering the statistics). The player can pick any door (with equal likelyhood of picking any of the 3), then the host must decide of the remaining two which one to open.

Re: Monty Hall Problem Simulation

that fixed it! I was defining the door the host opened before the the first choice! thank you, its working now

CD