Created
January 11, 2013 15:35
-
-
Save hackjoy/4511567 to your computer and use it in GitHub Desktop.
Problem: Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what's behind the doors, opens another door, say No. 3, which has a goat. He then says to you, "Do you want to pick door No. 2?" Is it to your advantage to swi…
This file contains 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
def createDoors | |
doors = [false, false, false] | |
# set one door equal to the car | |
doors[rand(3)] = true | |
doors | |
end | |
def openADoorThatHasAGoat(doors, userChoice) | |
# return the first false element after removing the users choice and a true value (if present) | |
([0, 1, 2] - [userChoice, doors.index(true)]).first | |
end | |
def changeUserChoice(choices) | |
# return the door remaining after removing the users original choice and the goat | |
([0, 1, 2] - choices).first | |
end | |
def play(switch_decision) | |
# create the doors and make 1 door == true | |
doors = createDoors() | |
# contestant picks their door | |
userChoice1 = rand(3) | |
# host removes a goat | |
hostChoice = openADoorThatHasAGoat(doors, userChoice1) | |
if switch_decision == "switch" | |
userChoice2 = changeUserChoice([userChoice1, hostChoice]) | |
# retun true if the index of the switch matches the index of true in doors | |
doors.index(true) == userChoice2 | |
elsif switch_decision == "dont switch" | |
doors.index(true) == userChoice1 | |
end | |
end | |
# games = 10000 | |
# wins = 0 | |
# games.times { wins += 1 if play("switch") } | |
# p ("#{100*wins/games}% win rate") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment