View Single Post
Old 15-08-2009, 12:51   #40
Paddy1
cf.addict
 
Join Date: Jul 2004
Posts: 350
Paddy1 has a reputation beyond reputePaddy1 has a reputation beyond reputePaddy1 has a reputation beyond reputePaddy1 has a reputation beyond reputePaddy1 has a reputation beyond reputePaddy1 has a reputation beyond reputePaddy1 has a reputation beyond reputePaddy1 has a reputation beyond reputePaddy1 has a reputation beyond reputePaddy1 has a reputation beyond reputePaddy1 has a reputation beyond reputePaddy1 has a reputation beyond reputePaddy1 has a reputation beyond repute
Re: Programming Challenges?

Apologies for the lack of indentation but I couldn't get it to look right. Anyway, here's my effort -

Spoiler: 

import java.util.Random;

public class MontyHall {

private enum Door { CAR, GOAT }

public static void main(String[] args) {

int switchWins = 0;
int iterations = 100000;


for (int i=1;i<=iterations;i++) {
if (doMontyHall())
switchWins++;
}

System.out.println("Switch wins = " + switchWins +
", No Switch wins = " + (iterations - switchWins) +
", Percentage wins from switching = " + ((float)(switchWins * 100) / iterations));


}

public static boolean doMontyHall() {
Door[] doors = new Door[3];
doors[0] = Door.GOAT;
doors[1] = Door.GOAT;
doors[2] = Door.GOAT;

Random r = new Random();
int carPosition = r.nextInt(3);
doors[carPosition] = Door.CAR;

int contestantSelection = r.nextInt(3);
boolean switchToWin = false;

if (doors[contestantSelection] == Door.GOAT)
switchToWin = true;

// This next step is not at all necessary to establish whether or not switching is beneficial
// and illustrates the point that once a door has been selected, the problem becomes a
// simple issue of only picking the correct door 1/3 times and the whole Host opening
// a door and asking is actually just a charade that serves to confuse people into thinking
// they now have a 50/50 chance of picking the correct door, which, of course they do, but
// 2/3 is always better than 50/50.

int hostSelection = r.nextInt(3);
while (hostSelection == contestantSelection || doors[hostSelection] == Door.CAR)
hostSelection = r.nextInt(3);

System.out.println("Contestant picked door " + contestantSelection +
", Host opened door " + hostSelection +
", Car was in door " + carPosition + ", Switch to win = " + switchToWin);

return switchToWin;

}
}

Paddy1 is offline   Reply With Quote