Created
October 28, 2013 19:54
-
-
Save loganhasson/7203462 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 MontyHall | |
attr_accessor :choice_index, :doors, :choice | |
attr_reader :switch_opt | |
@@win_count = 0 | |
@@loss_count = 0 | |
def initialize(switch_opt) | |
@doors = ["Car", "Goat", "Goat"].shuffle | |
@switch_opt = switch_opt | |
end | |
def self.win_count | |
@@win_count | |
end | |
def self.reset_win_and_loss_counts | |
@@win_count = 0 | |
@@loss_count = 0 | |
end | |
def self.loss_count | |
@@loss_count | |
end | |
def run | |
make_choice | |
host_choice | |
result | |
end | |
def make_choice | |
# puts self.doors.inspect | |
# puts "Which door? (0, 1, 2): " | |
# self.choice_index = gets.chomp.to_i | |
self.choice_index = 0 | |
self.choice = self.doors[choice_index] | |
self.doors.delete_at(self.choice_index) | |
self.doors.insert(self.choice_index, 0) | |
end | |
def host_choice | |
@host_choice = self.doors.find do |door| | |
door == "Goat" | |
end | |
@host_choice_index = self.doors.index(@host_choice) | |
# switch? | |
switch if self.switch_opt == true | |
self.doors.delete_at(@host_choice_index) | |
self.doors.insert(@host_choice_index, 0) | |
end | |
def switch? | |
puts self.doors.inspect | |
puts "Behind door #{@host_choice_index} is a goat. Wanna swap with the last door?" | |
input = gets.chomp | |
if input == 'y' | |
self.choice = self.doors.find do |door| | |
door != 0 | |
end | |
end | |
end | |
def switch | |
self.choice = self.doors.find do |door| | |
door != 0 | |
end | |
end | |
def result | |
#puts self.doors.inspect | |
if self.choice == "Car" | |
@@win_count += 1 | |
#puts "Winner!" | |
else | |
@@loss_count += 1 | |
#puts "Loser!" | |
end | |
end | |
end | |
MontyHall.reset_win_and_loss_counts | |
1000000.times do | |
MontyHall.new(true).run | |
end | |
puts "With Switching" | |
puts "Wins: #{MontyHall.win_count}" | |
puts "Losses: #{MontyHall.loss_count}" | |
puts "Win/Loss Percentage: #{(MontyHall.win_count.to_f/(MontyHall.win_count.to_f + MontyHall.loss_count.to_f)).round(2)*100}" | |
MontyHall.reset_win_and_loss_counts | |
1000000.times do | |
MontyHall.new(false).run | |
end | |
puts "" | |
puts "Without Switching" | |
puts "Wins: #{MontyHall.win_count}" | |
puts "Losses: #{MontyHall.loss_count}" | |
puts "Win/Loss Percentage: #{(MontyHall.win_count.to_f/(MontyHall.win_count.to_f + MontyHall.loss_count.to_f)).round(2)*100}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment