Skip to content

Instantly share code, notes, and snippets.

@sirupsen
Last active September 14, 2024 10:43
Show Gist options
  • Select an option

  • Save sirupsen/87ae5e79064354b0e4f81c8e1315f89b to your computer and use it in GitHub Desktop.

Select an option

Save sirupsen/87ae5e79064354b0e4f81c8e1315f89b to your computer and use it in GitHub Desktop.
switch_strategy = 0
no_switch_strategy = 0
n_simulations = 1_000_000
n_simulations.times do
winner_door = rand(3)
chosen_door = rand(3)
if winner_door == chosen_door
switch_strategy += 0
no_switch_strategy += 1
else
# The host always opens the other non-winning door and not your door, this
# reveals 'information' about your door.
revealed_door = [0, 1, 3] - [winner_door] - [chosen_door]
chosen_door = winner_door
switch_strategy += 1
no_switch_strategy += 0
end
end
puts "Switch strategy wins: #{switch_strategy} (#{(switch_strategy.to_f / n_simulations * 100).round(2)}%}"
puts "No Switch strategy wins: #{no_switch_strategy} (#{(no_switch_strategy.to_f / n_simulations * 100).round(2)}%)"
# Switch strategy wins: 666481 (66.65%}
# No Switch strategy wins: 333519 (33.35%)
@mlbright

Copy link
Copy Markdown

Lines 15 and 16 are not necessary. Thanks for the great napkin math article!

Revealed door:

possible_revealed_doors = [0, 1, 2] - [winner_door] - [chosen_door]
revealed_door = possible_revealed_doors.shuffle.pop

@sirupsen

Copy link
Copy Markdown
Author

Yep, it's there on purpose to make it easier for people to see why the strategy works :) More like prose!

@mgomes

mgomes commented Nov 5, 2021

Copy link
Copy Markdown

The simulation here doesn't simulate the Monty Hall problem, it's just showing the probability of picking the correct door when there are 3 doors to choose from.

For example, picking the right door off the bat doesn't imply the "no switch strategy" wins.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment