Skip to content

Instantly share code, notes, and snippets.

@Dzol
Forked from mwittrock/monty.rb
Created June 1, 2026 10:11
Show Gist options
  • Select an option

  • Save Dzol/eec7fdc6ba04b45e2124220544afe1af to your computer and use it in GitHub Desktop.

Select an option

Save Dzol/eec7fdc6ba04b45e2124220544afe1af to your computer and use it in GitHub Desktop.
A Ruby simulation of the Monty Hall problem.
# 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