Created
May 25, 2026 18:57
-
-
Save mwittrock/7c22c274cd4d0c5a4e5683ddc6c79efd to your computer and use it in GitHub Desktop.
A Ruby simulation of the Monty Hall problem.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # This program simulates the Monty Hall problem (https://en.wikipedia.org/wiki/Monty_Hall_problem). | |
| # Specifically, it counts how often the contestant wins by switching doors when given the choice | |
| # by the game show host. | |
| def contestant_wins? | |
| doors = [:car, :goat, :goat] | |
| indexes = 0...doors.size | |
| player_first_choice = rand(doors.size) | |
| host_choice = (indexes.select {|i| i != player_first_choice && doors[i] == :goat}).sample | |
| player_second_choice = indexes.find {|i| i != player_first_choice && i != host_choice} | |
| doors[player_second_choice] == :car | |
| end | |
| experiments = 10_000_000 | |
| wins = 0 | |
| experiments.times {wins += 1 if contestant_wins?} | |
| puts "Relative frequency of winning when switching doors: #{wins.to_f/experiments.to_f}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment