Monty Hall Problem in Ruby

Just for fun, the monty hall problem in ruby. Runs simulation one million times.


def monty_hall(switch)
  results = {switching: switch, wins: 0, losses: 0, count: 0, win_percentage: 0}
  (10**6).times.each do |n|
    prizes = [0,0,1].shuffle
    initial_selection = (0..2).to_a.sample
    other_doors = (0..2).to_a - [initial_selection]
    goat = other_doors.select{|n| prizes[n]==0}.sample
    available_selections = [initial_selection, (0..2).to_a - [initial_selection, goat]].flatten
    if switch 
      prize = prizes[available_selections[1]]
    else
      prize = prizes[available_selections[0]]
    end
    results[:wins] += 1 if prize == 1
    results[:losses] += 1 if prize == 0
    results[:count] += 1
  end
  results[:win_percentage] = ((results[:wins].to_f / results[:count].to_f) * 100).round(2)
  return results
end

Leave a Reply

Your email address will not be published. Required fields are marked *