Revision: 10514
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at January 2, 2009 22:35 by ronaldtm
Initial Code
/* * Monte Carlo simulation for the Monty Hall Problem: * http://en.wikipedia.org/wiki/Monty_Hall_problem. */ import java.util.* class MontyHall { static def RANDOM = new Random() def doors = ['car','goat','goat'] MontyHall() { Collections.shuffle(doors) } def pick_door() { RANDOM.nextInt(3) } def reveal_door(pick) { def available_doors = [0, 1, 2] - [doors.indexOf('car'), pick] available_doors[RANDOM.nextInt(available_doors.size())] } // Return true if the player won by staying // with their first choice, false otherwise. def staying_wins(pick) { won(pick) } // Return true if the player won by switching, false otherwise. def switching_wins(pick, open_door) { def switched_pick = ([0, 1, 2] - [open_door, pick])[0] won(switched_pick) } // Return true if the player's final pick hides a car, false otherwise. def won(pick) { doors[pick] == 'car' } public static void main(String[] args) { def ITERATIONS = 1000000 def staying = 0 def switching = 0 ITERATIONS.times { def mh = new MontyHall() def picked = mh.pick_door() def revealed = mh.reveal_door(picked) if (mh.staying_wins(picked)) staying++ if (mh.switching_wins(picked, revealed)) switching++ } def staying_rate = (staying / ITERATIONS) * 100 def switching_rate = (switching / ITERATIONS) * 100 println "Staying: ${staying_rate}%." println "Switching: ${switching_rate}%." } }
Initial URL
Initial Description
Initial Title
Monte Carlo simulation for the Monty Hall Problem
Initial Tags
groovy
Initial Language
Groovy