Skip to content

Instantly share code, notes, and snippets.

@hron
Created May 23, 2011 17:17
Show Gist options
  • Save hron/987084 to your computer and use it in GitHub Desktop.
Save hron/987084 to your computer and use it in GitHub Desktop.
Paradox Monty-Hall
#! /usr/bin/env ruby
require 'logger'
require 'pp'
class ThreeBoxGame
def initialize(options = {})
@double_choice = options[:double_choice] || false
@boxes = %w(1 2 3)
@box_with_price = @boxes.shuffle.first
@user_choice = @boxes.shuffle.first
@logger = Logger.new(STDOUT)
@logger.level = options[:log_level] || Logger::FATAL
status
end
def win?
status
remove_one_box_and_redefine_choice if @double_choice
status
@box_with_price == @user_choice
end
private
def remove_one_box_and_redefine_choice
box_to_remove = (@boxes - [ @box_with_price ]).shuffle.first
@boxes.delete(box_to_remove)
@user_choice = (@boxes - [ @user_choice ]).first
end
def status
@logger.debug "boxes: #{@boxes}"
@logger.debug "user_choice: #{@user_choice}"
@logger.debug "box_with_price: #{@box_with_price}"
end
end
# puts ThreeBoxGame.new(double_choice: false).win? ? "Win!" : "Lose!"
results = {
:single => { :win => 0, :lose => 0 },
:double => { :win => 0, :lose => 0 }
}
count_of_tests = 50_000
count_of_tests.times do
if ThreeBoxGame.new(double_choice: false).win?
results[:single][:win] += 1
else
results[:single][:lose] += 1
end
if ThreeBoxGame.new(double_choice: true).win?
results[:double][:win] += 1
else
results[:double][:lose] += 1
end
end
results[:double][:probability] = results[:double][:win].to_f / count_of_tests
results[:single][:probability] = results[:single][:win].to_f / count_of_tests
pp results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment