~pistos/monty-hall-rb

monty-hall-rb/monty-hall.rb -rw-r--r-- 1.3 KiB View raw
e34e17be — Pistos Add licence a month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# The Monty Hall Problem

# The host presents three options to the player.
# One of the options is the winning option.
# The player is asked to select one option.
# After the player tells the host his or her choice,
# the host removes one of the unselected options,
# stating (proving) that the removed option is not the winning option.
# The player is asked if he or she would like to change which option to select for the win.

# Should the player switch?
# Will switching provide worse odds, better odds, or the same odds of winning?

# https://en.wikipedia.org/wiki/Monty_Hall_problem

# ---------------------------------

# @return true iff player wins
def play_once(switch:)
  winning_choice = rand(3)
  contestant_choice = rand(3)
  host_choice = contestant_choice

  while host_choice == contestant_choice || host_choice == winning_choice
    host_choice = rand(3)
  end

  if switch
    contestant_choice = ([0,1,2] - [contestant_choice] - [host_choice])[0]
  end

  contestant_choice == winning_choice
end

NUM_GAMES = 1000

wins = 0
NUM_GAMES.times do
  if play_once(switch: false)
    wins += 1
  end
end

puts "Staying with original choice: player won #{wins} times out of #{NUM_GAMES}"

wins = 0
NUM_GAMES.times do
  if play_once(switch: true)
    wins += 1
  end
end

puts "Switching choices: player won #{wins} times out of #{NUM_GAMES}"