Lukas Z's Blog

Monty Hall Simulation

Here’s a simulation of the Monty Hall Problem.

# this is about http://en.wikipedia.org/wiki/Monty_Hall_problem

num_rounds = 5000
num_correct_guesses_keep = 0
num_correct_guesses_switch = 0

num_rounds.times do

        doors = [false, false, false]
        doors[rand(3)] = true

        # first pick = random

        player_pick = rand(3)
        show_bad_door = doors.index(true)

        # show a bad door that is not the price_door and not player's pick

        while (doors[show_bad_door] || show_bad_door == player_pick)
                show_bad_door = rand(3)
        end

        # second pick, player choses to switch to the other door
        
        remaining_doors = [0, 1, 2]
        remaining_doors.delete(show_bad_door)
        remaining_doors.delete(player_pick)

        player_switch_pick = remaining_doors.first        

        win = if doors[player_pick]
                num_correct_guesses_keep += 1
                "yes"
        else 
                "no"
        end

        win_switch = if doors[player_switch_pick]
                num_correct_guesses_switch += 1
                "yes"
        else 
                "no"
        end

        puts "doors: #{doors}, show_bad_door: #{show_bad_door}, "\
        "player keeps: #{player_pick}, player wins: #{win}, "\
        "player wins if he switches: #{win_switch}"

end

win_ratio = ( num_correct_guesses_keep.to_f / num_rounds.to_f * 100.to_f ).round(2)
win_ratio_pick = ( num_correct_guesses_switch.to_f / num_rounds.to_f * 100.to_f ).round(2)
puts "correct: #{num_correct_guesses_keep}, correct-switch: #{num_correct_guesses_switch}, "\
         "win-ratio: #{win_ratio}%, win-ratio switch: #{win_ratio_pick}%"

Switching really doubles the probability to win. Dang it. ;)

P.S.: You can follow me on Twitter.

Comments

Webmentions