Monty Hall Problem simulation

Suppose you’re on a game show, and you’re given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what’s behind the doors, opens another door, say No. 3, which has a goat. He then says to you, “Do you want to pick door No. 2?” Is it to your advantage to switch your choice? (Whitaker 1990)

http://en.wikipedia.org/wiki/Monty_Hall_problem

http://www.smartvideos.ru/probabilit-problem

#!/usr/bin/ruby

@cases = {
  :without_change => {
    :wins => 0,
    :looses => 0,
    :change? => lambda { false }
  },
  :with_change => {
    :wins => 0,
    :looses => 0,
    :change? => lambda { true }
  },
 :random_change => {
    :wins => 0,
    :looses => 0,
    :change? => lambda { rand(1) == 0 ? true : false }
  },

}

class Game
  def initialize
    @doors = [false, false, false]
    shuffle_gold
  end

  def shuffle_gold
    @wining_door_index = rand(@doors.size)
    @doors[@wining_door_index] = true
  end

  def player_make_choice
    @players_door_index = rand(@doors.size)
  end

  def win?
    @doors[@players_door_index]
  end

  def game_opens_loosing_door
    loosing_door_index = 0
    (1 .. @doors.size).each_with_index {|value, index| loosing_door_index = index if (index != @wining_door_index && index != @players_door_index) }
    @doors.delete(loosing_door_index)
  end
end

def play_games
  @cases.keys.each do |case_key|
    variant = @cases[case_key]
    game = Game.new()
    game.player_make_choice
    if game.win?
      variant[:wins] += 1
      next
    end
    game.game_opens_loosing_door

    if variant[:change?].call
      game.player_make_choice
    end

    if game.win?
      variant[:wins] += 1
    else
      variant[:looses] += 1
    end
  end
end

10000.times do
  play_games()
end

@cases.each do |key, stat|
  puts key
  puts "-------------------------"
  puts "wins: #{stat[:wins]}"
  puts "looses: #{stat[:looses]}"
  puts
end

1 Comment

  1. do you want to win a goat or sinbad on floppy disks?

Comments are closed.

© 2024 Gudasoft

Theme by Anders NorénUp ↑