Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Monty Hall
--lua 5.3 --Testing the Monty Hall paradox -- --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 switch your choice? --randomise the randomiser math.randomseed(os.time()) --a simple function to return "won" or "lost" based on true or false function wonString(won) if won then return "won" else return "lost" end end --start a counter for wins local wins = 0 --the main function function montyHall(swap_choice) local won = false --we've lost until we win local doors = {"a", "b", "c"} --name our doors local winning_door = doors[math.random(#doors)] --chose a door to be the winner local my_choice = doors[math.random(#doors)] --choose a door to bet upon function pickADoorToRemove() --function return the index of a door that is not the winner, and not the player choice. this could be 1 or 2 doors local r = math.random(#doors) --randomly pick one of the doors if doors[r] ~= winning_door and r~= my_choice then --check it's not the winning door, or the current player choice return r --if it's not, then this is the door to remove else return pickADoorToRemove() --if it is, run this function again, until we find the right door. end end table.remove(doors, pickADoorToRemove()) --remove one of the remaining doors, one that isn't the winning door, not the current choice if swap_choice then local my_new_choice = doors[math.random(#doors)] if my_new_choice == winning_door then won = true wins = wins + 1 end --print("You chose door "..my_choice.." then swapped to door "..my_new_choice.." and you "..wonString(won).."(it was door "..winning_door..")") else if my_choice == winning_door then won = true wins = wins + 1 end -- print("You chose door "..my_choice..", stuck with it, and you "..wonString(won)) end end --set the number of times to test local times_to_test = 200 --Do the tests, swapping the choice of door when prompted for i=1,times_to_test do montyHall(true) end print("Swapping doors, you won "..wins.." of "..times_to_test) --reset the win score wins = 0 --Do the the tests, not swapping doors when prompted for i=1,times_to_test do montyHall(false) end print("Not swapping doors, you won "..wins.." of "..times_to_test)
run
|
edit
|
history
|
help
0
Creating habits v2, Lua (WIP)
Newton-Raphson method for the square root
Basic Lehmer RNG implementation using closures
xml panel repeater
zzz
hack
cases
missing element
CC: LDInterface
Kegs Scores ... FOOOOOOTBALLLLLL