Monty Hall problem: Difference between revisions

Lua/Torch
(→‎{{header|Kotlin}}: Updated example see https://github.com/dkandalov/rosettacode-kotlin for details)
(Lua/Torch)
Line 2,191:
print(player.wins)
end</lang>
 
=={{header|Lua/Torch}}==
<lang lua>function montyHall(n)
local car = torch.LongTensor(n):random(3) -- door with car
local choice = torch.LongTensor(n):random(3) -- player's choice
local opens = torch.LongTensor(n):random(2):csub(1):mul(2):csub(1) -- -1 or +1
local iscarchoice = choice:eq(car)
local nocarchoice = 1-iscarchoice
opens[iscarchoice] = (((opens + choice - 1) % 3):abs() + 1)[iscarchoice]
opens[nocarchoice] = (6 - car - choice)[nocarchoice]
local change = torch.LongTensor(n):bernoulli() -- 0: stay, 1: change
local win = iscarchoice:long():cmul(1-change) + nocarchoice:long():cmul(change)
return car, choice, opens, change, win
end
 
function montyStats(n)
local car, pchoice, opens, change, win = montyHall(n)
local change_and_win = change [ win:byte()]:sum()/ change :sum()*100
local no_change_and_win = (1-change)[ win:byte()]:sum()/(1-change):sum()*100
local change_and_win_not = change [1-win:byte()]:sum()/ change :sum()*100
local no_change_and_win_not = (1-change)[1-win:byte()]:sum()/(1-change):sum()*100
 
print(string.format(" %9s %9s" , "no change", "change" ))
print(string.format("win %8.4f%% %8.4f%%", no_change_and_win , change_and_win ))
print(string.format("win not %8.4f%% %8.4f%%", no_change_and_win_not, change_and_win_not))
end
 
montyStats(1e7)</lang>
 
Output for 10 million samples:
<pre>
no change change
win 33.3008% 66.6487%
win not 66.6992% 33.3513%</pre>
 
=={{header|Mathematica}}==
Anonymous user