Created
December 19, 2012 00:29
-
-
Save AitorATuin/4333384 to your computer and use it in GitHub Desktop.
MontyHall en lua
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
#!/usr/bin/lua | |
-- | |
-- Monty Hall | |
-- | |
-- | |
local chooseDoor = function () | |
return math.random(1,3) | |
end | |
local simulate = function (goodDoor, choosenDoor, change) | |
if (choosenDoor == goodDoor) then | |
-- Acertamos, por lo que cambiar es fallo y no cambiar acierto | |
if change then return false else return true end | |
else | |
-- No hemos acertado, por lo que cambiar es ok, no cambiar fallo | |
if change then return true else return false end | |
end | |
end | |
local initDoors = function () | |
math.randomseed(os.time()); | |
end | |
local function main(argc, argv) | |
if not argv[1] or not tonumber(argv[1]) then | |
print("Uso: MontyHall.lua n (número de veces a iterar)") | |
os.exit() | |
end | |
print("Iniciando Puertas ...") | |
initDoors() | |
print("Simulando elección sin cambio") | |
local n = tonumber(argv[1]) | |
local sc = 0 | |
local snc = 0 | |
for i=1, n do | |
if simulate(chooseDoor(), chooseDoor(), true) then | |
sc = sc + 1 | |
end | |
end | |
print("Simulando elección con cambio") | |
for i=1, n do | |
if simulate(chooseDoor(), chooseDoor(), false) then | |
snc = snc + 1 | |
end | |
end | |
print("Resultados") | |
print(string.format("Con cambio %d/%d = %.3f", n, sc, sc/n)) | |
print(string.format("Sin cambio %d/%d = %.3f", n, snc, snc/n)) | |
end | |
main(#arg, arg) |
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
~/Projects/Lua/MontyHill ᐅ lua MontyHill.lua 5000000 | |
Iniciando Puertas ... | |
Simulando elección sin cambio | |
Simulando elección con cambio | |
Resultados | |
Con cambio 5000000/3332835 = 0.667 | |
Sin cambio 5000000/1668029 = 0.334 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment