Created
April 8, 2010 20:41
-
-
Save quinn/360514 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Array | |
| def sum; inject( nil ) { |sum,x| sum ? sum+x : x }; end | |
| def mean; sum / size; end | |
| def random; self[rand(size)]; end | |
| end | |
| class TheThreeDoors | |
| attr_accessor :prize, :strategy, :revealed, :picked, :final_selection | |
| def initialize strategy | |
| @prize = rand(3) + 1 | |
| @strategy = strategy | |
| end | |
| def pick_one(num) | |
| @picked = num | |
| end | |
| def reveal! | |
| doors = [1,2,3] | |
| doors.delete(@prize) | |
| doors.delete(@picked) | |
| @revealed = doors.random | |
| end | |
| def run_strategy | |
| if strategy == :switch | |
| @final_selection = [1,2,3].select{|door| door != @picked && door != @revealed}.first | |
| else | |
| @final_selection = @picked | |
| end | |
| end | |
| def win | |
| if @final_selection == @prize | |
| return 1.0 | |
| else | |
| return 0.0 | |
| end | |
| end | |
| end | |
| wins = [] | |
| 10000.times do |trial| | |
| doors = TheThreeDoors.new(:switch) | |
| doors.pick_one rand(3)+1 | |
| doors.reveal! | |
| # puts "run the strategy!!" | |
| doors.run_strategy | |
| # puts "we picked #{doors.picked}" | |
| # puts "winning door #{doors.prize}" | |
| # puts "reveal a wrong door: #{doors.revealed}" | |
| # puts "final selectio: #{doors.final_selection}" | |
| # puts "" | |
| wins << doors.win | |
| # puts "the prize is #{doors.prize}" | |
| # puts "\n" | |
| end | |
| puts "we won #{wins.mean} times" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment