Posted By

ronaldtm on 01/02/09


Tagged

groovy montyhall montecarlo


Versions (?)

Monte Carlo simulation for the Monty Hall Problem


 / Published in: Groovy
 

  1. /*
  2.  * Monte Carlo simulation for the Monty Hall Problem:
  3.  * http://en.wikipedia.org/wiki/Monty_Hall_problem.
  4.  */
  5.  
  6. import java.util.*
  7.  
  8. class MontyHall {
  9. static def RANDOM = new Random()
  10.  
  11. def doors = ['car','goat','goat']
  12.  
  13. MontyHall() {
  14. Collections.shuffle(doors)
  15. }
  16.  
  17. def pick_door() {
  18. RANDOM.nextInt(3)
  19. }
  20.  
  21. def reveal_door(pick) {
  22. def available_doors = [0, 1, 2] - [doors.indexOf('car'), pick]
  23. available_doors[RANDOM.nextInt(available_doors.size())]
  24. }
  25.  
  26. // Return true if the player won by staying
  27. // with their first choice, false otherwise.
  28. def staying_wins(pick) {
  29. won(pick)
  30. }
  31.  
  32. // Return true if the player won by switching, false otherwise.
  33. def switching_wins(pick, open_door) {
  34. def switched_pick = ([0, 1, 2] - [open_door, pick])[0]
  35. won(switched_pick)
  36. }
  37.  
  38. // Return true if the player's final pick hides a car, false otherwise.
  39. def won(pick) {
  40. doors[pick] == 'car'
  41. }
  42.  
  43. public static void main(String[] args) {
  44. def ITERATIONS = 1000000
  45.  
  46. def staying = 0
  47. def switching = 0
  48.  
  49. ITERATIONS.times {
  50. def mh = new MontyHall()
  51. def picked = mh.pick_door()
  52. def revealed = mh.reveal_door(picked)
  53. if (mh.staying_wins(picked)) staying++
  54. if (mh.switching_wins(picked, revealed)) switching++
  55. }
  56.  
  57. def staying_rate = (staying / ITERATIONS) * 100
  58. def switching_rate = (switching / ITERATIONS) * 100
  59.  
  60. println "Staying: ${staying_rate}%."
  61. println "Switching: ${switching_rate}%."
  62. }
  63. }

Report this snippet  

You need to login to post a comment.