Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
台上有三扇门,其中一扇门后藏有现金100万,主持人叫你选择其中一扇门后,然后主持人在余下的门中排除一个没有现金的门,这时问你要不要更换选择?
require 'pp'
class Door
# name: :A, :B, :C
# has_money: true / false
attr_accessor :name, :has_money
def initialize(name)
@name = name
@has_money = false
end
end
class Person
# selected_door :A, :B, :C
attr_accessor :selected_door
end
class TestCase1
attr_accessor :doors, :person
def initialize
@doors = [Door.new(:A), Door.new(:B), Door.new(:C)]
@doors[rand(3)].has_money = true
@person = Person.new
@person.selected_door = [:A, :B, :C][rand(3)]
end
def success?
@person.selected_door == @doors.detect { |door| door.has_money == true }.name
end
end
class TestCase2
attr_accessor :doors, :person
def initialize
@doors = [Door.new(:A), Door.new(:B), Door.new(:C)]
@doors[rand(3)].has_money = true
@person = Person.new
@person.selected_door = [:A, :B, :C][rand(3)]
# puts "First times:choose #{@person.selected_door}"
change_to_another_door
end
def change_to_another_door
leave_doors = @doors.select { |door| door.name != @person.selected_door }
#puts "left doors #{leave_doors.collect{|d| d.name }.join(', ')}"
if success?
@person.selected_door = leave_doors.collect { |door| door.name }[rand(2)] # will always choose wrong one
else
@person.selected_door = leave_doors.detect { |door| door.has_money == true }.name # will always choose right one
end
end
def success?
@person.selected_door == @doors.detect { |door| door.has_money == true }.name
end
end
n = 10000
test1_cases = []
n.times do |i|
test1_cases << TestCase1.new
end
success_cases = test1_cases.select { |t| t.success? }
puts "1. sucess cases count #{success_cases.size}/#{n} [#{success_cases.size/n.to_f}] "
test2_cases = []
n.times do |i|
test2_cases << TestCase2.new
end
success_cases = test2_cases.select { |t| t.success? }
puts "2. sucess cases count #{success_cases.size}/#{n} [#{success_cases.size/n.to_f}]"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment