Skip to content

Instantly share code, notes, and snippets.

@macek macek/monty_hall.rb
Created Jun 1, 2010

Embed
What would you like to do?
require "benchmark"
ITERATIONS = (ARGV[0] || 10000).to_i
def pick(set)
set[rand(set.size)]
end
def trial(method)
wins = 0
ITERATIONS.times do
wins+=1 if send(method)
end
"#{method}: {iterations:#{ITERATIONS}, rate:#{wins*1.0/ITERATIONS}}"
end
def marek_ruby
# randomize doors for good measure :)
doors = [:one, :two, :three].shuffle
winner = [pick(doors)]
losers = doors - winner
choice = pick(doors)
if winner.include?(choice)
# open random junk door
doors -= [pick(losers)]
else
# open opposite junk door
doors -= (losers - [choice])
end
# switch choice
doors -= [choice]
# return
doors == winner
end
def marek_c
door_win = rand(3)
door_guess = rand(3)
case door_guess
when 0
door_open = door_win == 1 ? 2 : 1
switch_door = door_open == 2 ? 1 : 2
when 1
door_open = door_win == 0 ? 2 : 0
switch_door = door_open == 2 ? 0 : 2
when 2
door_open = door_win == 0 ? 1 : 0
switch_door = door_open == 1 ? 0 : 1
end
switch_door == door_win
end
buffer = []
Benchmark.bm(10) do |b|
[:marek_ruby, :marek_c].each do |m|
b.report m.to_s do
buffer << trial(m)
end
end
end
puts buffer
# user system total real
# marek_ruby 0.080000 0.000000 0.080000 ( 0.074415)
# marek_c 0.000000 0.000000 0.000000 ( 0.006399)
# marek_ruby: {iterations:10000, rate:0.6668}
# marek_c: {iterations:10000, rate:0.666}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.