Monty Hall problem: Difference between revisions

m
m (→‎{{header|Picat}}: Added {{out}})
(43 intermediate revisions by 17 users not shown)
Line 47:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">V stay = 0
V sw = 0
 
Line 71:
 
print(‘Stay = ’stay)
print(‘Switch = ’sw)</langsyntaxhighlight>
 
=={{header|8086 Assembly}}==
 
<langsyntaxhighlight lang="asm">time: equ 2Ch ; MS-DOS syscall to get current time
puts: equ 9 ; MS-DOS syscall to print a string
cpu 8086
Line 153:
nsw: db 'When not switching doors: $'
db '*****'
number: db 13,10,'$'</langsyntaxhighlight>
 
{{out}}
Line 161:
 
=={{header|ActionScript}}==
<langsyntaxhighlight lang="actionscript">package {
import flash.display.Sprite;
 
Line 192:
}
}
}</langsyntaxhighlight>
Output:
<pre>Switching wins 18788 times. (62.626666666666665%)
Line 198:
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">-- Monty Hall Game
 
with Ada.Text_Io; use Ada.Text_Io;
Line 273:
Put_Line("%");
 
end Monty_Stats;</langsyntaxhighlight>
Results
<pre>Stay : count 34308 = 34.31%
Line 284:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<langsyntaxhighlight lang="algol68">INT trials=100 000;
 
PROC brand = (INT n)INT: 1 + ENTIER (n * random);
Line 337:
print(("Changing: ", percent(change winning), new line ));
print(("New random choice: ", percent(random winning), new line ))
)</langsyntaxhighlight>
Sample output:
<pre>
Line 346:
 
=={{header|APL}}==
<langsyntaxhighlight lang="apl"> ∇ Run runs;doors;i;chosen;cars;goats;swap;stay;ix;prices
[1] ⍝0: Monthy Hall problem
[2] ⍝1: http://rosettacode.org/wiki/Monty_Hall_problem
Line 360:
[12] ⎕←'Swap: ',(2⍕100×(swap÷runs)),'% it''s a car'
[13] ⎕←'Stay: ',(2⍕100×(stay÷runs)),'% it''s a car'
∇</langsyntaxhighlight>
<pre>
Run 100000
Line 371:
{{trans|Nim}}
 
<langsyntaxhighlight lang="rebol">stay: 0
swit: 0
 
Line 394:
 
print ["Stay:" stay]
print ["Switch:" swit]</langsyntaxhighlight>
 
{{out}}
Line 402:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="ahk">#SingleInstance, Force
Iterations = 1000
Loop, %Iterations%
Line 435:
Mode := Mode = 2 ? 2*rand - 1: Mode
Return, Mode = 1 ? 6 - guess - show = actual : guess = actual
}</langsyntaxhighlight>
Sample output:
<pre>
Line 448:
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">#!/bin/gawk -f
 
# Monty Hall problem
Line 504:
simulate(RAND)
}</langsyntaxhighlight>
Sample output:
<langsyntaxhighlight lang="awk">bash$ ./monty_hall.awk
 
Monty Hall problem simulation:
Line 514:
Algorithm switch: prize count = 6655, = 66.55%
Algorithm random: prize count = 4991, = 49.91%
bash$</langsyntaxhighlight>
 
=={{header|BASIC}}==
==={{header|ANSI BASIC}}===
{{works with|QuickBasic|4.5}}
{{trans|JavaXPL0}}
{{works with|Decimal BASIC}}
<lang qbasic>RANDOMIZE TIMER
<syntaxhighlight lang="basic">
DIM doors(3) '0 is a goat, 1 is a car
100 PROGRAM MontyHallProblem
CLS
110 DEF NGames = 10000
switchWins = 0
120 RANDOMIZE
stayWins = 0
130 LET NWins = 0
FOR plays = 0 TO 32767
140 FOR Game = 0 TO NGames
winner = INT(RND * 3) + 1
150 IF IsGameWon(0) <> 0 THEN LET NWins = NWins + 1
doors(winner) = 1'put a winner in a random door
160 NEXT Game
choice = INT(RND * 3) + 1'pick a door, any door
170 PRINT "NOT switching doors wins car in ";
DO
180 PRINT USING "##.#": NWins / NGames * 100;
shown = INT(RND * 3) + 1
190 PRINT "% of games."
'don't show the winner or the choice
200 LET NWins = 0
LOOP WHILE doors(shown) = 1 OR shown = choice
210 FOR Game = 0 TO NGames
stayWins = stayWins + doors(choice) 'if you won by staying, count it
220 IF IsGameWon(1) <> 0 THEN LET NWins = NWins + 1
switchWins = switchWins + doors(3 - choice - shown) 'could have switched to win
230 NEXT Game
doors(winner) = 0 'clear the doors for the next test
240 PRINT "But switching doors wins car in ";
NEXT plays
250 PRINT USING "##.#": NWins / NGames * 100;
PRINT "Switching wins"; switchWins; "times."
260 PRINT "Staying% wins";of stayWins; "timesgames."</lang>
270 END
Output:
280 REM ***
<pre>Switching wins 21805 times.
290 EXTERNAL FUNCTION IsGameWon(Sw)
Staying wins 10963 times.</pre>
300 REM Play one game.
 
310 REM Switching if and only if Sw <> 0.
320 REM Returns 1 if the game is won, 0 otherwise.
330 LET Car = INT(RND * 3) ! Randomly place car behind a door.
340 LET Player0 = INT(RND * 3) ! Player randomly chooses a door.
350 DO
360 LET Monty = INT(RND * 3) ! Monty opens door revealing a goat.
370 LOOP UNTIL (Monty <> Car) AND (Monty <> Player0)
380 IF Sw <> 0 THEN ! Player switches TO remaining door.
390 DO
400 LET Player = INT(RND * 3)
410 LOOP UNTIL (Player <> Player0) AND (Player <> Monty)
420 ELSE
430 LET Player = Player0 ! Player sticks with original door.
440 END IF
450 IF Player = Car THEN
460 LET IsGameWon = 1
470 ELSE
480 LET IsGameWon = 0
490 END IF
500 END FUNCTION
</syntaxhighlight>
{{out}}(example)
<pre>
NOT switching doors wins car in 32.3% of games.
But switching doors wins car in 67.3% of games.
</pre>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">
<lang BASIC256>
numTiradas = 1000000
permanece = 0
Line 568 ⟶ 594:
print "Si cambia, tiene un "; cambia / numTiradas * 100; "% de probabilidades de ganar."
end
</syntaxhighlight>
</lang>
 
==={{header|BBC BASIC}}===
<syntaxhighlight lang="bbcbasic"> total% = 10000
FOR trial% = 1 TO total%
prize_door% = RND(3) : REM. The prize is behind this door
guess_door% = RND(3) : REM. The contestant guesses this door
IF prize_door% = guess_door% THEN
REM. The contestant guessed right, reveal either of the others
reveal_door% = RND(2)
IF prize_door% = 1 reveal_door% += 1
IF prize_door% = 2 AND reveal_door% = 2 reveal_door% = 3
ELSE
REM. The contestant guessed wrong, so reveal the non-prize door
reveal_door% = prize_door% EOR guess_door%
ENDIF
stick_door% = guess_door% : REM. The sticker doesn't change his mind
swap_door% = guess_door% EOR reveal_door% : REM. but the swapper does
IF stick_door% = prize_door% sticker% += 1
IF swap_door% = prize_door% swapper% += 1
NEXT trial%
PRINT "After a total of ";total%;" trials,"
PRINT "The 'sticker' won ";sticker%;" times (";INT(sticker%/total%*100);"%)"
PRINT "The 'swapper' won ";swapper%;" times (";INT(swapper%/total%*100);"%)"</syntaxhighlight>
Output:
<pre>
After a total of 10000 trials,
The 'sticker' won 3379 times (33%)
The 'swapper' won 6621 times (66%)
</pre>
 
==={{header|Euphoria}}===
<syntaxhighlight lang="euphoria">integer switchWins, stayWins
switchWins = 0
stayWins = 0
 
integer winner, choice, shown
 
for plays = 1 to 10000 do
winner = rand(3)
choice = rand(3)
while 1 do
shown = rand(3)
if shown != winner and shown != choice then
exit
end if
end while
stayWins += choice = winner
switchWins += 6-choice-shown = winner
end for
printf(1, "Switching wins %d times.\n", switchWins)
printf(1, "Staying wins %d times.\n", stayWins)
</syntaxhighlight>
{{out}} (sample)
<pre>
Switching wins 6697 times.
Staying wins 3303 times.
</pre>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">
' version 19-01-2019
' compile with: fbc -s console
 
Const As Integer max = 1000000
Randomize Timer
 
Dim As UInteger i, car_door, chosen_door, montys_door, stay, switch
 
For i = 1 To max
car_door = Fix(Rnd * 3) + 1
chosen_door = Fix(Rnd * 3) + 1
If car_door <> chosen_door Then
montys_door = 6 - car_door - chosen_door
Else
Do
montys_door = Fix(Rnd * 3) + 1
Loop Until montys_door <> car_door
End If
'Print car_door,chosen_door,montys_door
' stay
If car_door = chosen_door Then stay += 1
' switch
If car_door = 6 - montys_door - chosen_door Then switch +=1
Next
 
Print Using "If you stick to your choice, you have a ##.## percent" _
+ " chance to win"; stay / max * 100
Print Using "If you switched, you have a ##.## percent chance to win"; _
switch / max * 100
 
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End
</syntaxhighlight>
{{out}}
<pre>
If you stick to your choice, you have a 33.32 percent chance to win
If you switched, you have a 66.68 percent chance to win
</pre>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "MontyH.bas"
110 RANDOMIZE
120 LET NUMGAMES=1000
Line 585 ⟶ 712:
220 PRINT "Num of games:";NUMGAMES
230 PRINT "Wins not changing doors:";NOTCHANGING,NOTCHANGING/NUMGAMES*100;"% of total."
240 PRINT "Wins changing doors:",CHANGING,CHANGING/NUMGAMES*100;"% of total."</langsyntaxhighlight>
 
==={{header|Liberty BASIC}}===
{{trans|Quick BASIC}}
{{works with|Just BASIC}}
<syntaxhighlight lang="lb">
DIM doors(3) '0 is a goat, 1 is a car
 
total = 10000 'set desired number of iterations
switchWins = 0
stayWins = 0
 
FOR plays = 1 TO total
winner = INT(RND(1) * 3) + 1
doors(winner) = 1'put a winner in a random door
choice = INT(RND(1) * 3) + 1'pick a door, any door
DO
shown = INT(RND(1) * 3) + 1
'don't show the winner or the choice
LOOP WHILE doors(shown) = 1 OR shown = choice
if doors(choice) = 1 then
stayWins = stayWins + 1 'if you won by staying, count it
else
switchWins = switchWins + 1'could have switched to win
end if
doors(winner) = 0 'clear the doors for the next test
NEXT
PRINT "Result for ";total;" games."
PRINT "Switching wins "; switchWins; " times."
PRINT "Staying wins "; stayWins; " times."
</syntaxhighlight>
{{out}} (example)
<pre>
Result for 10000 games.
Switching wins 6634 times.
Staying wins 3366 times.</pre>
 
==={{header|Minimal BASIC}}===
{{trans|ANSI BASIC}}
{{works with|BASICA}}
<syntaxhighlight lang="basic">
10 REM Monty Hall problem
20 LET N = 10000
30 RANDOMIZE
40 LET W = 0
50 FOR G = 0 TO N
60 LET S = 0
70 GOSUB 230
80 IF V = 0 THEN 100
90 LET W = W+1
100 NEXT G
110 PRINT "NOT switching doors wins car in";
120 PRINT W/N*100; "per cent of games."
130 LET W = 0
140 FOR G = 0 TO N
150 LET S = 1
160 GOSUB 230
170 IF V = 0 THEN 190
180 LET W = W+1
190 NEXT G
200 PRINT "But switching doors wins car in";
210 PRINT W/N*100; "per cent of games."
220 END
230 REM ** Is game won?
240 REM Play one game.
250 REM Switching if and only if S <> 0.
260 REM Randomly place car behind a door.
270 LET C = INT(RND*3)
280 REM Player randomly chooses a door.
290 LET P0 = INT(RND*3)
300 REM Monty opens door revealing a goat.
310 LET M = INT(RND*3)
320 IF M = C THEN 310
330 IF M = P0 THEN 310
340 IF S = 0 THEN 410
350 REM Player switches to remaining door.
360 LET P = INT(RND*3)
370 IF P = P0 THEN 360
380 IF P = M THEN 360
390 GOTO 430
400 REM Player sticks with original door.
410 LET P = P0
420 REM Victory?
430 IF P <> C THEN 460
440 LET V = 1
450 RETURN
460 LET V = 0
470 RETURN
</syntaxhighlight>
 
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">Structure wins
stay.i
redecide.i
EndStructure
 
#goat = 0
#car = 1
Procedure MontyHall(*results.wins)
Dim Doors(2)
Doors(Random(2)) = #car
 
player = Random(2)
Select Doors(player)
Case #car
*results\redecide + #goat
*results\stay + #car
Case #goat
*results\redecide + #car
*results\stay + #goat
EndSelect
EndProcedure
OpenConsole()
#Tries = 1000000
Define results.wins
 
For i = 1 To #Tries
MontyHall(@results)
Next
PrintN("Trial runs for each option: " + Str(#Tries))
PrintN("Wins when redeciding: " + Str(results\redecide) + " (" + StrD(results\redecide / #Tries * 100, 2) + "% chance)")
PrintN("Wins when sticking: " + Str(results\stay) + " (" + StrD(results\stay / #Tries * 100, 2) + "% chance)")
Input()</syntaxhighlight>
 
Output:<pre>Trial runs for each option: 1000000
Wins when redeciding: 666459 (66.65% chance)
Wins when sticking: 333541 (33.35% chance)</pre>
 
==={{header|QuickBASIC}}===
{{works with|QuickBasic|4.5}}
{{trans|Java}}
<syntaxhighlight lang="qbasic">RANDOMIZE TIMER
DIM doors(3) '0 is a goat, 1 is a car
CLS
switchWins = 0
stayWins = 0
FOR plays = 0 TO 32767
winner = INT(RND * 3) + 1
doors(winner) = 1'put a winner in a random door
choice = INT(RND * 3) + 1'pick a door, any door
DO
shown = INT(RND * 3) + 1
'don't show the winner or the choice
LOOP WHILE doors(shown) = 1 OR shown = choice
stayWins = stayWins + doors(choice) 'if you won by staying, count it
switchWins = switchWins + doors(3 - choice - shown) 'could have switched to win
doors(winner) = 0 'clear the doors for the next test
NEXT plays
PRINT "Switching wins"; switchWins; "times."
PRINT "Staying wins"; stayWins; "times."</syntaxhighlight>
Output:
<pre>Switching wins 21805 times.
Staying wins 10963 times.</pre>
 
==={{header|Run BASIC}}===
{{trans|Quick BASIC}}
{{works with|Just BASIC}}
<syntaxhighlight lang="runbasic">
input "Number of tries;";tries ' gimme the number of iterations
FOR plays = 1 TO tries
winner = INT(RND(1) * 3) + 1
doors(winner) = 1 'put a winner in a random door
choice = INT(RND(1) * 3) + 1 'pick a door please
[DO] shown = INT(RND(1) * 3) + 1
' ------------------------------------------
' don't show the winner or the choice
if doors(shown) = 1 then goto [DO]
if shown = choice then goto [DO]
if doors(choice) = 1 then
stayWins = stayWins + 1 ' if you won by staying, count it
else
switchWins = switchWins + 1 ' could have switched to win
end if
doors(winner) = 0 'clear the doors for the next test
NEXT
PRINT " Result for ";tries;" games."
PRINT "Switching wins ";switchWins; " times."
PRINT " Staying wins ";stayWins; " times."</syntaxhighlight>
 
==={{header|Sinclair ZX81 BASIC}}===
Line 596 ⟶ 903:
switcher wins;</pre>
but I take it that the point is to demonstrate the outcome to people who may <i>not</i> see that that's what is going on. I have therefore written the program in a deliberately naïve style, not assuming anything.
<langsyntaxhighlight lang="basic"> 10 PRINT " WINS IF YOU"
20 PRINT "STICK","SWITCH"
30 LET STICK=0
Line 610 ⟶ 917:
130 IF NEWGUESS=CAR THEN LET SWITCH=SWITCH+1
140 NEXT I
150 PRINT AT 2,0;STICK,SWITCH</langsyntaxhighlight>
{{out}}
<pre> WINS IF YOU
Line 616 ⟶ 923:
341 659</pre>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">OPTION BASE 0
DIM puertas(3)
 
==={{header|True BASIC}}===
<lang basic>
LET numTiradas = 1000000
 
FOR i = 10 TO numTiradas
LET pta_coche = INT(RND * 3) + 1
LET puertas(pta_coche) = 1
LET pta_elegida = INT(RND * 3) + 1
DO
IF pta_coche <> pta_elegida THEN
LET pta_montys = 6INT(RND -* pta_coche3) -+ pta_elegida1
LOOP WHILE puertas(pta_montys) = 1 OR pta_montys = pta_elegida
IF puertas(pta_elegida) = 1 THEN
LET cambia = cambia + 1
ELSE
LET permanece = permanece + 1
DO
LET pta_montys = INT(RND * 3) + 1
LOOP UNTIL pta_montys <> pta_coche
END IF
LET puertas(pta_coche) = 0
! mantener elección
IF pta_coche = pta_elegida THEN LET permanece = permanece + 1
! cambiar elección
IF pta_coche = 6 - pta_montys - pta_elegida THEN LET cambia = cambia + 1
NEXT i
 
PRINT "Cambiar gana el"; permanece / numTiradas * 100; "% de las veces."
PRINT "Mantenerse gana el"; cambia / numTiradas * 100; "% de las veces."
END</syntaxhighlight>
END
</lang>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">
numTiradas = 1000000
 
for i = 1 to numTiradas
=={{header|BBC BASIC}}==
pta_coche = int(ran(3)) + 1
<lang bbcbasic> total% = 10000
pta_elegida = int(ran(3)) + 1
FOR trial% = 1 TO total%
if pta_coche <> pta_elegida then
prize_door% = RND(3) : REM. The prize is behind this door
pta_montys = 6 - pta_coche - pta_elegida
guess_door% = RND(3) : REM. The contestant guesses this door
else
IF prize_door% = guess_door% THEN
repeat
REM. The contestant guessed right, reveal either of the others
pta_montys = int(ran(3)) + 1
reveal_door% = RND(2)
until pta_montys <> pta_coche
IF prize_door% = 1 reveal_door% += 1
end if
IF prize_door% = 2 AND reveal_door% = 2 reveal_door% = 3
// manteenr elección
ELSE
if pta_coche = pta_elegida then permanece = permanece + 1 : fi
REM. The contestant guessed wrong, so reveal the non-prize door
// cambiar elección
reveal_door% = prize_door% EOR guess_door%
if pta_coche = 6 - pta_montys - pta_elegida then cambia = cambia + 1 : fi
ENDIF
next i
stick_door% = guess_door% : REM. The sticker doesn't change his mind
 
swap_door% = guess_door% EOR reveal_door% : REM. but the swapper does
print "Si mantiene su eleccion, tiene un ", permanece / numTiradas * 100, "% de probabilidades de ganar."
IF stick_door% = prize_door% sticker% += 1
print "Si cambia, tiene un ", cambia / numTiradas * 100, "% de probabilidades de ganar."
IF swap_door% = prize_door% swapper% += 1
end
NEXT trial%
</syntaxhighlight>
PRINT "After a total of ";total%;" trials,"
PRINT "The 'sticker' won ";sticker%;" times (";INT(sticker%/total%*100);"%)"
PRINT "The 'swapper' won ";swapper%;" times (";INT(swapper%/total%*100);"%)"</lang>
Output:
<pre>
After a total of 10000 trials,
The 'sticker' won 3379 times (33%)
The 'swapper' won 6621 times (66%)
</pre>
 
=={{header|C}}==
<syntaxhighlight lang="c">//Evidence of the Monty Hall solution of marquinho1986 in C [github.com/marquinho1986]
 
<lang c>//Evidence of the Monty Hall solution.
 
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <time.h>
#include <math.h>
#define NumSim 1000000000 // one billion of simulations! using the Law of large numbers concept [https://en.wikipedia.org/wiki/Law_of_large_numbers]
 
void main() {
#define GAMES 3000000
unsigned long int i,stay=0;
 
int ChosenDoor,WinningDoor;
int main(void){
unsigned i, j, k, choice, winsbyswitch=0,bool door[3]={0,0,0};
 
srand(time(NULL)); //initialize random seed.
for(i=0; i<GAMES; i++){
for(i=0;i<=NumSim;i++){
door[0] = (!(rand()%2)) ? 1: 0; //give door 1 either a car or a goat randomly.
if(door[0]) door[1]=door[2]=0; //if 1st door has car, give other doors goats.
WinningDoor=rand() % 3; // choosing winning door.
else{ door[1] = (!(rand()%2)) ? 1: 0; door[2] = (!door[1]) ? 1: 0; } //else, give 2nd door car or goat, give 3rd door what's left.
choice = rand()%3; //choose a random door.
ChosenDoor=rand() % 3; // selected door.
 
//if the next door has a goat, and the following door has a car, or vice versa, you'd win if you switch.
if(door[WinningDoor]=true,door[ChosenDoor])stay++;
if(((!(door[((choice+1)%3)])) && (door[((choice+2)%3)])) || (!(door[((choice+2)%3)]) && (door[((choice+1)%3)]))) winsbyswitch++;
}
door[WinningDoor]=false;
printf("\nAfter %u games, I won %u by switching. That is %f%%. ", GAMES, winsbyswitch, (float)winsbyswitch*100.0/(float)i);
}
}
</lang>
printf("\nAfter %lu games, I won %u by staying. That is %f%%. and I won by switching %lu That is %f%%",NumSim, stay, (float)stay*100.0/(float)i,abs(NumSim-stay),100-(float)stay*100.0/(float)i);
}
</syntaxhighlight>
 
Output of one run:
 
<pre>After 30000001000000000 games, I won 1999747333332381 by switchingstaying. That is 6633.658233333238%. and I won by switching 666667619 That is 66.666762% </pre>
 
=={{header|C sharp|C#}}==
{{trans|Java}}
<langsyntaxhighlight lang="csharp">using System;
 
class Program
Line 740 ⟶ 1,048:
Console.Out.WriteLine("Switching wins " + switchWins + " times.");
}
}</langsyntaxhighlight>
Sample output:
<pre>
Line 748 ⟶ 1,056:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <cstdlib>
#include <ctime>
Line 804 ⟶ 1,112:
int wins_change = check(games, true);
std::cout << "staying: " << 100.0*wins_stay/games << "%, changing: " << 100.0*wins_change/games << "%\n";
}</langsyntaxhighlight>
Sample output:
staying: 33.73%, changing: 66.9%
 
=={{header|Chapel}}==
 
<lang chapel>use Random;
'''Version 1''' : using task parallelism.
 
<syntaxhighlight lang="chapel">
use Random;
 
param doors: int = 3;
Line 860 ⟶ 1,172:
writeln( "Both methods are equal." );
}
</syntaxhighlight>
</lang>
 
Sample output:
<pre>
Line 866 ⟶ 1,179:
Wins by switching: 646 or 64.6%
Switching is the superior method.
</pre>
 
'''Version 2''' : using data parallelism.
 
<syntaxhighlight lang="chapel">
use Random;
 
config const numGames = 100_000_000;
 
var switch, stick: uint;
 
// have a separate RNG for each task; add together the results at the end
forall i in 1..numGames
with (var rand = new RandomStream(uint, parSafe = false), + reduce stick)
{
var chosen_door = rand.getNext() % 3;
var winner_door = rand.getNext() % 3;
if chosen_door == winner_door then
stick += 1;
}
 
// if you lost by sticking it means you would have won by switching
switch = numGames - stick;
writeln("Over ", numGames, " games:\n - switching wins ",
100.0*switch / numGames, "% of the time and\n - sticking wins ",
100.0*stick / numGames, "% of the time");
 
</syntaxhighlight>
 
Sample output:
<pre>
Over 1000000 games:
- switching wins 66.6937% of the time and
- sticking wins 33.3063% of the time
</pre>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(ns monty-hall-problem
(:use [clojure.contrib.seq :only (shuffle)]))
 
Line 884 ⟶ 1,231:
(range times))]
(str "wins " wins " times out of " times)))
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="clojure">monty-hall-problem> (println "staying:" (simulate true 1000))
staying: wins 337 times out of 1000
nil
Line 891 ⟶ 1,238:
switching: wins 638 times out of 1000
nil
</syntaxhighlight>
</lang>
 
=={{header|COBOL}}==
{{works with|OpenCOBOL}}
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. monty-hall.
 
Line 983 ⟶ 1,330:
END PROGRAM get-rand-int.
 
END PROGRAM monty-hall.</langsyntaxhighlight>
 
{{out}}
Line 992 ⟶ 1,339:
 
=={{header|ColdFusion}}==
<langsyntaxhighlight lang="cfm"><cfscript>
function runmontyhall(num_tests) {
// number of wins when player switches after original selection
Line 1,033 ⟶ 1,380:
}
runmontyhall(10000);
</cfscript></langsyntaxhighlight>
Output:
<pre>
Line 1,040 ⟶ 1,387:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun make-round ()
(let ((array (make-array 3
:element-type 'bit
Line 1,054 ⟶ 1,401:
 
(defun won? (array i)
(= 1 (bit array i)))</langsyntaxhighlight>
<langsyntaxhighlight lang="lisp">CL-USER> (progn (loop repeat #1=(expt 10 6)
for round = (make-round)
for initial = (random 3)
Line 1,072 ⟶ 1,419:
#1# 1/100))))))
Stay: 33.2716%
Switch: 66.6593%</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lisp">
;Find out how often we win if we always switch
(defun rand-elt (s)
Line 1,089 ⟶ 1,436:
(defun monty-trials (n)
(count t (loop for x from 1 to n collect (monty))))
</syntaxhighlight>
</lang>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.random;
 
void main() {
Line 1,122 ⟶ 1,469:
 
writefln("Switching/Staying wins: %d %d", switchWins, stayWins);
}</langsyntaxhighlight>
{{out}}
<pre>Switching/Staying wins: 66609 33391</pre>
Line 1,128 ⟶ 1,475:
=={{header|Dart}}==
The class Game attempts to hide the implementation as much as possible, the play() function does not use any specifics of the implementation.
<langsyntaxhighlight lang="dart">int rand(int max) => (Math.random()*max).toInt();
 
class Game {
Line 1,210 ⟶ 1,557:
play(10000,false);
play(10000,true);
}</langsyntaxhighlight>
<pre>playing without switching won 33.32%
playing with switching won 67.63%</pre>
Line 1,218 ⟶ 1,565:
{{works with|Delphi|XE10}}
{{libheader| System.SysUtils}}
<langsyntaxhighlight Delphilang="delphi">program MontyHall;
 
{$APPTYPE CONSOLE}
Line 1,267 ⟶ 1,614:
WriteLn('Switching wins ' + IntToStr(switchWins) + ' times.');
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>Staying wins 333253 times.
Line 1,276 ⟶ 1,623:
{{trans|C#}}
 
<langsyntaxhighlight lang="dyalect">var switchWins = 0
var stayWins = 0
Line 1,295 ⟶ 1,642:
print("Staying wins \(stayWins) times.")
print("Switching wins \(switchWins) times.")</langsyntaxhighlight>
 
{{out}}
Line 1,301 ⟶ 1,648:
<pre>Staying wins 286889 times.
Switching wins 713112 times.</pre>
 
=={{header|EasyLang}}==
{{trans|FreeBASIC}}
<syntaxhighlight>
max = 1000000
for i = 1 to max
car_door = randint 3
chosen_door = randint 3
if car_door <> chosen_door
montys_door = 6 - car_door - chosen_door
else
repeat
montys_door = randint 3
until montys_door <> car_door
.
.
if car_door = chosen_door
stay += 1
.
if car_door = 6 - montys_door - chosen_door
switch += 1
.
.
print "If you stick to your choice, you have a " & stay / max * 100 & " percent chance to win"
print "If you switched, you have a " & switch / max * 100 & " percent chance to win"
</syntaxhighlight>
{{out}}
<pre>
If you stick to your choice, you have a 33.36 percent chance to win
If you switched, you have a 66.64 percent chance to win
</pre>
 
=={{header|Eiffel}}==
<langsyntaxhighlight lang="eiffel">
note
description: "[
Line 1,617 ⟶ 1,995:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,637 ⟶ 2,015:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule MontyHall do
def simulate(n) do
{stay, switch} = simulate(n, 0, 0)
Line 1,659 ⟶ 2,037:
end
 
MontyHall.simulate(10000)</langsyntaxhighlight>
 
{{out}}
Line 1,669 ⟶ 2,047:
=={{header|Emacs Lisp}}==
{{trans|Picolisp}}
<langsyntaxhighlight lang="lisp">(defun montyhall (keep)
(let ((prize (random 3))
(choice (random 3)))
Line 1,683 ⟶ 2,061:
(dotimes (i 10000)
(and (montyhall nil) (setq cnt (1+ cnt))))
(message "Strategy switch: %.3f%%" (/ cnt 100.0)))</langsyntaxhighlight>
 
{{out}}
Line 1,689 ⟶ 2,067:
Strategy keep: 34.410%
Strategy switch: 66.430%
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
type Prize
enum do int GOAT, CAR end
type Door
model
int id
Prize prize
new by int =id, Prize =prize do end
fun asText = text by block do return "(id:" + me.id + ", prize:" + me.prize.value + ")" end
end
type Player
model
Door choice
fun choose = void by List doors
me.choice = doors[random(3)]
end
end
type Monty
model
fun setPrize = void by List doors, Prize prize
doors[random(3)].prize = prize
end
end
type MontyHallProblem
int ITERATIONS = 1000000
Map counter = text%int[ "keep" => 0, "switch" => 0 ]
writeLine("Simulating " + ITERATIONS + " games:")
for int i = 0; i < ITERATIONS; i++
if i % 100000 == 0 do write(".") end
^|three numbered doors with no cars for now|^
List doors = Door[Door(1, Prize.GOAT), Door(2, Prize.GOAT), Door(3, Prize.GOAT)]
Monty monty = Monty() # set up Monty
monty.setPrize(doors, Prize.CAR) # Monty randomly sets the car behind one door
Player player = Player() # set up the player
player.choose(doors) # the player makes a choice
^|here Monty opens a door with a goat;
|behind the ones that are still closed there is a car and a goat,
|so that the player *always* wins by keeping or switching.
|^
counter[when(player.choice.prize == Prize.CAR, "keep", "switch")]++
end
writeLine()
writeLine(counter)
</syntaxhighlight>
{{out}}
<pre>
Simulating 1000000 games:
..........
[keep:332376,switch:667624]
</pre>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(monty_hall).
 
-export([main/0]).
Line 1,718 ⟶ 2,148:
false -> OpenDoor
end.
</syntaxhighlight>
</lang>
Sample Output:
<pre>Switching wins 66595 times.
Staying wins 33405 times.</pre>
 
=={{header|Euphoria}}==
<lang euphoria>integer switchWins, stayWins
switchWins = 0
stayWins = 0
 
integer winner, choice, shown
 
for plays = 1 to 10000 do
winner = rand(3)
choice = rand(3)
while 1 do
shown = rand(3)
if shown != winner and shown != choice then
exit
end if
end while
stayWins += choice = winner
switchWins += 6-choice-shown = winner
end for
printf(1, "Switching wins %d times\n", switchWins)
printf(1, "Staying wins %d times\n", stayWins)
</lang>
Sample Output:<br />
:Switching wins 6697 times<br />
:Staying wins 3303 times
 
=={{header|F_Sharp|F#}}==
I don't bother with having Monty "pick" a door, since you only win if you initially pick a loser in the switch strategy and you only win if you initially pick a winner in the stay strategy so there doesn't seem to be much sense in playing around the background having Monty "pick" doors. Makes it pretty simple to see why it's always good to switch.
<langsyntaxhighlight lang="fsharp">open System
let monty nSims =
let rnd = new Random()
Line 1,763 ⟶ 2,167:
 
let Wins (f:unit -> int) = seq {for i in [1..nSims] -> f()} |> Seq.sum
printfn "Stay: %d wins out of %d - Switch: %d wins out of %d" (Wins StayGame) nSims (Wins SwitchGame) nSims</langsyntaxhighlight>
Sample Output:
<pre>Stay: 332874 wins out of 1000000 - Switch: 667369 wins out of 1000000</pre>
 
I had a very polite suggestion that I simulate Monty's "pick" so I'm putting in a version that does that. I compare the outcome with my original outcome and, unsurprisingly, show that this is essentially a noop that has no bearing on the output, but I (kind of) get where the request is coming from so here's that version...
<langsyntaxhighlight lang="fsharp">let montySlower nSims =
let rnd = new Random()
let MontyPick winner pick =
Line 1,799 ⟶ 2,203:
 
let Wins (f:unit -> int) = seq {for i in [1..nSims] -> f()} |> Seq.sum
printfn "Stay: %d wins out of %d - Switch: %d wins out of %d" (Wins StayGame) nSims (Wins SwitchGame) nSims</langsyntaxhighlight>
 
=={{header|Forth}}==
 
===version 1===
<langsyntaxhighlight lang="forth">include random.fs
 
variable stay-wins
Line 1,820 ⟶ 2,224:
cr switch-wins @ . [char] / emit . ." switching wins" ;
 
1000 trials</langsyntaxhighlight>
 
or in iForth:
 
<langsyntaxhighlight lang="forth">0 value stay-wins
0 value switch-wins
 
Line 1,837 ⟶ 2,241:
dup 0 ?DO trial LOOP
CR stay-wins DEC. ." / " dup DEC. ." staying wins,"
CR switch-wins DEC. ." / " DEC. ." switching wins." ;</langsyntaxhighlight>
 
With output:
Line 1,848 ⟶ 2,252:
{{works with|GNU Forth}}
While Forthers are known (and regarded) for always simplifying the problem, I think version 1 is missing the point here. The optimization can only be done if one already understands the game. For what it's worth, here is a simulation that takes all the turns of the game.
<langsyntaxhighlight Forthlang="forth">require random.fs
here seed !
 
Line 1,876 ⟶ 2,280:
' keep IS applyStrategy run ." Keep door => " .result cr
' switch IS applyStrategy run ." Switch door => " .result cr
bye</langsyntaxhighlight>
 
{{out}}
Line 1,886 ⟶ 2,290:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">PROGRAM MONTYHALL
IMPLICIT NONE
Line 1,931 ⟶ 2,335:
WRITE(*, "(A,F6.2,A)") "Chance of winning by switching is", real(switchcount)/trials*100, "%"
 
END PROGRAM MONTYHALL</langsyntaxhighlight>
Sample Output
Chance of winning by not switching is 32.82%
Chance of winning by switching is 67.18%
 
=={{header|FreeBASICFōrmulæ}}==
{{FormulaeEntry|page=https://formulae.org/?script=examples/Monty_Hall_problem}}
<lang freebasic>' version 19-01-2019
' compile with: fbc -s console
 
'''Solution'''
Const As Integer max = 1000000
Randomize Timer
 
The following program makes a given number of simulations. On each, three options are evaluated:
Dim As UInteger i, car_door, chosen_door, montys_door, stay, switch
 
* If the player keeps his/her selection
For i = 1 To max
* If the player randomly chooses between hs/her selection and the other (closed) door.
car_door = Fix(Rnd * 3) + 1
* If the player switches his/her selection
chosen_door = Fix(Rnd * 3) + 1
If car_door <> chosen_door Then
montys_door = 6 - car_door - chosen_door
Else
Do
montys_door = Fix(Rnd * 3) + 1
Loop Until montys_door <> car_door
End If
'Print car_door,chosen_door,montys_door
' stay
If car_door = chosen_door Then stay += 1
' switch
If car_door = 6 - montys_door - chosen_door Then switch +=1
Next
 
Finally, it shows the number of wins for each case.
Print Using "If you stick to your choice, you have a ##.## percent" _
+ " chance to win"; stay / max * 100
Print Using "If you switched, you have a ##.## percent chance to win"; _
switch / max * 100
 
[[File:Fōrmulæ - Monty Hall problem 01.png]]
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End</lang>
{{out}}
<pre>If you stick to your choice, you have a 33.32 percent chance to win
If you switched, you have a 66.68 percent chance to win</pre>
 
[[File:Fōrmulæ - Monty Hall problem 02.png]]
=={{header|Fōrmulæ}}==
 
[[File:Fōrmulæ - Monty Hall problem 03.png]]
 
It can be seen that:
 
* If the player keeps his/her selection, he/she wins around 1/3 of times
* If the player randomly chooses between his/her selection and the other (closed) door, he/she wins around 1/2 of times
* If the player switches his/her selection, he/she wins around 2/3 of times
 
The following variation shows the evolution of the probabilities for each case:
 
[[File:Fōrmulæ - Monty Hall problem 04.png]]
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
[[File:Fōrmulæ - Monty Hall problem 05.png]]
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
[[File:Fōrmulæ - Monty Hall problem 06.png]]
In '''[https://formulae.org/?example=Monty_Hall_problem this]''' page you can see the program(s) related to this task and their results.
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,011 ⟶ 2,400:
fmt.Printf("Keeper Wins: %d (%3.2f%%)",
keeperWins, (float32(keeperWins) / floatGames * 100))
}</langsyntaxhighlight>
Output:
<pre>
Line 2,019 ⟶ 2,408:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import System.Random (StdGen, getStdGen, randomR)
 
trials :: Int
Line 2,052 ⟶ 2,441:
percent n ++ "% of the time."
percent n = show $ round $
100 * (fromIntegral n) / (fromIntegral trials)</langsyntaxhighlight>
 
{{libheader|mtl}}
With a <tt>State</tt> monad, we can avoid having to explicitly pass around the <tt>StdGen</tt> so often. <tt>play</tt> and <tt>cars</tt> can be rewritten as follows:
 
<langsyntaxhighlight lang="haskell">import Control.Monad.State
 
play :: Bool -> State StdGen Door
Line 2,077 ⟶ 2,466:
cars n switch g = (numcars, new_g)
where numcars = length $ filter (== Car) prize_list
(prize_list, new_g) = runState (replicateM n (play switch)) g</langsyntaxhighlight>
 
Sample output (for either implementation):
<langsyntaxhighlight lang="haskell">The switch strategy succeeds 67% of the time.
The stay strategy succeeds 34% of the time.</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">REAL :: ndoors=3, doors(ndoors), plays=1E4
 
DLG(NameEdit = plays, DNum=1, Button='Go')
Line 2,115 ⟶ 2,504:
WRITE(ClipBoard, Name) plays, switchWins, stayWins
 
END</langsyntaxhighlight>
<langsyntaxhighlight lang="hicest">! plays=1E3; switchWins=695; stayWins=305;
! plays=1E4; switchWins=6673; stayWins=3327;
! plays=1E5; switchWins=66811; stayWins=33189;
! plays=1E6; switchWins=667167; stayWins=332833;</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main(arglist)
 
rounds := integer(arglist[1]) | 10000
Line 2,140 ⟶ 2,529:
write("Strategy 2 'Switching' won ", real(strategy2) / rounds )
 
end</langsyntaxhighlight>
 
Sample Output:<pre>Monty Hall simulation for 10000 rounds.
Line 2,147 ⟶ 2,536:
 
=={{header|Io}}==
<langsyntaxhighlight Iolang="io">keepWins := 0
switchWins := 0
doors := 3
Line 2,169 ⟶ 2,558:
.. "Keeping the same door won #{keepWins} times.\n"\
.. "Game played #{times} times with #{doors} doors.") interpolate println
</syntaxhighlight>
</lang>
Sample output:<pre>Switching to the other door won 66935 times.
Keeping the same door won 33065 times.
Line 2,178 ⟶ 2,567:
The core of this simulation is picking a random item from a set
 
<langsyntaxhighlight lang="j">pick=: {~ ?@#</langsyntaxhighlight>
 
And, of course, we will be picking one door from three doors
 
<langsyntaxhighlight lang="j">DOORS=:1 2 3</langsyntaxhighlight>
 
But note that the simulation code should work just as well with more doors.
Line 2,188 ⟶ 2,577:
Anyways the scenario where the contestant's switch or stay strategy makes a difference is where Monty has picked from the doors which are neither the user's door nor the car's door.
 
<langsyntaxhighlight lang="j">scenario=: ((pick@-.,])pick,pick) bind DOORS</langsyntaxhighlight>
 
(Here, I have decided that the result will be a list of three door numbers. The first number in that list is the number Monty picks, the second number represents the door the user picked, and the third number represents the door where the car is hidden.)
Line 2,194 ⟶ 2,583:
Once we have our simulation test results for the scenario, we need to test if staying would win. In other words we need to test if the user's first choice matches where the car was hidden:
 
<langsyntaxhighlight lang="j">stayWin=: =/@}.</langsyntaxhighlight>
 
In other words: drop the first element from the list representing our test results -- this leaves us with the user's choice and the door where the car was hidden -- and then insert the verb <code>=</code> between those two values.
Line 2,200 ⟶ 2,589:
We also need to test if switching would win. In other words, we need to test if the user would pick the car from the doors other than the one Monty picked and the one the user originally picked:
 
<langsyntaxhighlight lang="j">switchWin=: pick@(DOORS -. }:) = {:</langsyntaxhighlight>
 
In other words, start with our list of all doors and then remove the door the monty picked and the door the user picked, and then pick one of the remaining doors at random (the pick at random part is only significant if there were originally more than 3 doors) and see if that matches the door where the car is.
Line 2,206 ⟶ 2,595:
Finally, we need to run the simulation a thousand times and count how many times each strategy wins:
 
<langsyntaxhighlight lang="j"> +/ (stayWin,switchWin)@scenario"0 i.1000
320 680</langsyntaxhighlight>
 
Or, we could bundle this all up as a defined word. Here, the (optional) left argument "names" the doors and the right argument says how many simulations to run:
 
<langsyntaxhighlight lang="j">simulate=:3 :0
1 2 3 simulate y
:
Line 2,221 ⟶ 2,610:
labels=. ];.2 'limit stay switch '
smoutput labels,.":"0 y,+/r
)</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight lang="j"> simulate 1000
limit 1000
stay 304
switch 696 </langsyntaxhighlight>
 
Or, with more doors (and assuming this does not require new rules about how Monty behaves or how the player behaves):
 
<langsyntaxhighlight lang="j"> 1 2 3 4 simulate 1000
limit 1000
stay 233
switch 388 </langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.util.Random;
public class Monty{
public static void main(String[] args){
Line 2,262 ⟶ 2,651:
System.out.println("Staying wins " + stayWins + " times.");
}
}</langsyntaxhighlight>
Output:
<pre>Switching wins 21924 times.
Line 2,271 ⟶ 2,660:
===Extensive Solution===
 
This solution can test with n doors, the difference in probability for switching is shown to diminish as the number of doors increases*.
 
<langsyntaxhighlight lang="javascript">
function montyhall(tests, doors) {
'use strict';
Line 2,312 ⟶ 2,701:
};
}
</syntaxhighlight>
</lang>
 
{{out}}
<langsyntaxhighlight lang="javascript">
montyhall(1000, 3)
Object {stayWins: "349 34.9%", switchWins: "651 65.1%"}
Line 2,322 ⟶ 2,711:
montyhall(1000, 5)
Object {stayWins: "202 20.2%", switchWins: "265 26.5%"}
</syntaxhighlight>
</lang>
 
In the above code/problem version with n doors, only one "losing" door is opened/shown by the show host before the possibility of switch. There is a generalization to the problem in which the show host progressively opens losing doors one by one until two remains. In this case, the win probability of switching increases as the number of door increases. This has been discussed in a [https://www.researchgate.net/publication/262373808_A_generalization_of_the_Monty_Hall_Problem] 2009 article.
 
Slight modification of the script above for modularity inside of HTML.
<langsyntaxhighlight lang="javascript"><html>
 
<body>
Line 2,373 ⟶ 2,764:
}
 
</script></langsyntaxhighlight>
'''Output:'''
<langsyntaxhighlight lang="javascript">(1000, 3)
First Door Wins: 346 | 34.6%
Switching Door Wins: 654 | 65.4%</langsyntaxhighlight>
 
===Basic Solution===
 
<!-- http://blog.dreasgrech.com/2011/09/simulating-monty-hall-problem.html -->
<langsyntaxhighlight lang="javascript">
var totalGames = 10000,
selectDoor = function () {
Line 2,427 ⟶ 2,818:
console.log("Wins when not switching door", play(false));
console.log("Wins when switching door", play(true));
</syntaxhighlight>
</lang>
 
{{out}}
<langsyntaxhighlight lang="javascript">
Playing 10000 games
Wins when not switching door 3326
Wins when switching door 6630
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
Line 2,453 ⟶ 2,844:
This solution is based on the observation: {{quote|If I initially guessed the winning door and didn't switch, or if I initially guessed a losing door but then switched, I've won.}}
 
<langsyntaxhighlight lang="jq">def rand:
input as $r
| if $r < . then $r else rand end;
Line 2,470 ⟶ 2,861:
"Switching wins \(.switchWins) times\n" ;
 
1e3, 1e6 | logical_montyHall</langsyntaxhighlight>
 
====Simulation====
{{trans|Kotlin}}
<langsyntaxhighlight lang="jq">def rand:
input as $r
| if $r < . then $r else rand end;
Line 2,499 ⟶ 2,890:
"Switching wins \(.switchWins) times\n" ;
1e3, 1e6 | montyHall</langsyntaxhighlight>
{{out}}
<pre>
Line 2,517 ⟶ 2,908:
 
'''The Literal Simulation Function'''
<langsyntaxhighlight Julialang="julia">using Printf
 
function play_mh_literal{T<:Integer}(ncur::T=3, ncar::T=1)
Line 2,539 ⟶ 2,930:
return (isstickwin, isswitchwin)
end
</syntaxhighlight>
</lang>
 
'''The Clean Simulation Function'''
<syntaxhighlight lang="julia">
<lang Julia>
function play_mh_clean{T<:Integer}(ncur::T=3, ncar::T=1)
ncar < ncur || throw(DomainError())
Line 2,554 ⟶ 2,945:
return (isstickwin, isswitchwin)
end
</syntaxhighlight>
</lang>
 
'''Supporting Functions'''
<syntaxhighlight lang="julia">
<lang Julia>
function mh_results{T<:Integer}(ncur::T, ncar::T,
nruns::T, play_mh::Function)
Line 2,602 ⟶ 2,993:
return nothing
end
</syntaxhighlight>
</lang>
 
'''Main'''
<syntaxhighlight lang="julia">
<lang Julia>
for i in 3:5, j in 1:(i-2)
show_simulation(i, j, 10^5)
end
</syntaxhighlight>
</lang>
 
This code shows, for a variety of configurations, the results for 3 solutions: literal simulation, clean simulation, analytic. Stick is the percentage of times that the player wins a car by sticking to an initial choice. Switch is the winning percentage the comes with switching one's selection following the goat reveal. Improvement is the ratio of switch to stick.
Line 2,674 ⟶ 3,065:
(0.33241,0.66759)
</pre>
=={{header|K}}==
<syntaxhighlight lang="k">
montyhall:{t:,/ 1_ x {`prng@`t[];ch:1?3;pr:1?3;sw:1?2;$[sw;a:ch=pr;a:~(ch=pr)];a}\0N;("KEEP %";(+/t)%x;"SWAP %";(+/~t)%x)}
 
montyhall 100000
</syntaxhighlight>
 
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// version 1.1.2
 
import java.util.Random
Line 2,704 ⟶ 3,101:
fun main(args: Array<String>) {
montyHall(1_000_000)
}</langsyntaxhighlight>
Sample output:
{{out}}
Line 2,712 ⟶ 3,109:
Switching wins 666330 times
</pre>
 
=={{header|Liberty BASIC}}==
<lang lb>
'adapted from BASIC solution
DIM doors(3) '0 is a goat, 1 is a car
 
total = 10000 'set desired number of iterations
switchWins = 0
stayWins = 0
 
FOR plays = 1 TO total
winner = INT(RND(1) * 3) + 1
doors(winner) = 1'put a winner in a random door
choice = INT(RND(1) * 3) + 1'pick a door, any door
DO
shown = INT(RND(1) * 3) + 1
'don't show the winner or the choice
LOOP WHILE doors(shown) = 1 OR shown = choice
if doors(choice) = 1 then
stayWins = stayWins + 1 'if you won by staying, count it
else
switchWins = switchWins + 1'could have switched to win
end if
doors(winner) = 0 'clear the doors for the next test
NEXT
PRINT "Result for ";total;" games."
PRINT "Switching wins "; switchWins; " times."
PRINT "Staying wins "; stayWins; " times."
</lang>
Output:
<pre>
Result for 10000 games.
Switching wins 6634 times.
Staying wins 3366 times.</pre>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function playgame(player)
local car = math.random(3)
local pchoice = player.choice()
Line 2,764 ⟶ 3,127:
for i = 1, 20000 do playgame(player) end
print(player.wins)
end</langsyntaxhighlight>
 
=={{header|Lua/Torch}}==
<langsyntaxhighlight 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
Line 2,793 ⟶ 3,156:
end
 
montyStats(1e7)</langsyntaxhighlight>
 
Output for 10 million samples:
Line 2,802 ⟶ 3,165:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Enum Strat {Stay, Random, Switch}
Line 2,847 ⟶ 3,210:
}
CheckIt
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,856 ⟶ 3,219:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica"> montyHall[nGames_] :=
Module[{r, winningDoors, firstChoices, nStayWins, nSwitchWins, s},
r := RandomInteger[{1, 3}, nGames];
Line 2,865 ⟶ 3,228:
Grid[{{"Strategy", "Wins", "Win %"}, {"Stay", Row[{nStayWins, "/", nGames}], s=N[100 nStayWins/nGames]},
{"Switch", Row[{nSwitchWins, "/", nGames}], 100 - s}}, Frame -> All]]</langsyntaxhighlight>
 
;Usage:
<syntaxhighlight lang Mathematica="mathematica">montyHall[100000]</langsyntaxhighlight>
 
[[File:MontyHall.jpg]]
 
=={{header|MATLAB}}==
<syntaxhighlight lang="matlab">
<lang MATLAB>function montyHall(numDoors,numSimulations)
wins = ceil(3*rand(1e8,1)) - ceil(3*rand(1e8,1))
mprintf('chance to win for staying: %1.6f %%\nchance to win for changing: %1.6f %%', 100*length(wins(wins==0))/length(wins), 100*length(wins(wins<>0))/length(wins))
</syntaxhighlight>
 
OUTPUT:
 
<syntaxhighlight lang="matlab">
chance to win for staying: 33.334694 %
chance to win for changing: 66.665306 %
</syntaxhighlight>
 
<syntaxhighlight lang="matlab">
 
function montyHall(numDoors,numSimulations)
 
assert(numDoors > 2);
Line 2,928 ⟶ 3,305:
disp(sprintf('Switch win percentage: %f%%\nStay win percentage: %f%%\n', [switchedDoors(1)/sum(switchedDoors),stayed(1)/sum(stayed)] * 100));
end</langsyntaxhighlight>
 
Output:
<langsyntaxhighlight MATLABlang="matlab">>> montyHall(3,100000)
Switch win percentage: 66.705972%
Stay win percentage: 33.420062%</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">fn montyHall choice switch =
(
doors = #(false, false, false)
Line 2,960 ⟶ 3,337:
iterations = 10000
format ("Stay strategy:%\%\n") (iterate iterations false)
format ("Switch strategy:%\%\n") (iterate iterations true)</langsyntaxhighlight>
Output:
<langsyntaxhighlight lang="maxscript">Stay strategy:33.77%
Switch strategy:66.84%</langsyntaxhighlight>
 
 
=={{header|Modula-2}}==
{{trans|XPL0|<code>CARDINAL</code> (unsigned integer) used instead of integer.}}
{{works with|ADW Modula-2|any (Compile with the linker option ''Console Application'').}}
<syntaxhighlight lang="modula2">
MODULE MontyHallProblem;
 
FROM STextIO IMPORT
WriteLn, WriteString;
FROM RandomNumbers IMPORT
Randomize, Rnd;
FROM SRealIO IMPORT
WriteFixed;
 
CONST
NGames = 10000; (* number of games simulated *)
VAR
NWins, Game: CARDINAL;
 
PROCEDURE IsGameWon(Sw: BOOLEAN): BOOLEAN;
(* Play one game. *)
VAR
Car, Player, Player0, Monty: CARDINAL;
BEGIN
Car := Rnd(3); (* Randomly place car behind a door. *)
Player0 := Rnd(3); (* Player randomly chooses a door. *)
REPEAT
Monty := Rnd(3); (* Monty opens door revealing a goat. *)
UNTIL (Monty <> Car) AND (Monty <> Player0);
IF Sw THEN
(* Player switches to remaining door. *)
REPEAT
Player := Rnd(3);
UNTIL (Player <> Player0) AND (Player <> Monty)
ELSE
Player := Player0 (* Player sticks with original door. *)
END;
RETURN (Player = Car);
END IsGameWon;
 
BEGIN
Randomize(0);
NWins := 0;
FOR Game := 0 TO NGames DO
IF IsGameWon(FALSE) THEN
NWins := NWins + 1
END
END;
WriteString('NOT switching doors wins car in ');
WriteFixed(FLOAT(NWins) / FLOAT(NGames) * 100.0, 1, 4);
WriteString('% of games.');
WriteLn;
NWins := 0;
FOR Game := 0 TO NGames DO
IF IsGameWon(TRUE) THEN
NWins := NWins + 1
END
END;
WriteString('But switching doors wins car in ');
WriteFixed(FLOAT(NWins) / FLOAT(NGames) * 100.0, 1, 4);
WriteString('% of games.');
WriteLn;
END MontyHallProblem.
</syntaxhighlight>
{{out}}(example)
<pre>
NOT switching doors wins car in 33.4% of games.
But switching doors wins car in 66.5% of games.
</pre>
 
=={{header|NetRexx}}==
Line 2,969 ⟶ 3,416:
{{trans|REXX}}
{{trans|PL/I}}
<langsyntaxhighlight lang="netrexx">/* NetRexx ************************************************************
* 30.08.2013 Walter Pachl translated from Java/REXX/PL/I
**********************************************************************/
Line 3,003 ⟶ 3,450:
method r3 static
rand=random()
return rand.nextInt(3) + 1</langsyntaxhighlight>
Output
<pre>
Line 3,012 ⟶ 3,459:
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import random
 
randomize()
Line 3,049 ⟶ 3,496:
 
echo "Stay = ",stay
echo "Switch = ",switch</langsyntaxhighlight>
Output:
<pre>Stay = 337
Line 3,055 ⟶ 3,502:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let trials = 10000
 
type door = Car | Goat
Line 3,083 ⟶ 3,530:
strat (100. *. (float n /. float trials)) in
msg "switch" switch;
msg "stay" stay</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">test(trials)={
my(stay=0,change=0);
for(i=1,trials,
Line 3,098 ⟶ 3,545:
};
 
test(1e4)</langsyntaxhighlight>
 
Output:
Line 3,106 ⟶ 3,553:
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">program MontyHall;
 
uses
Line 3,156 ⟶ 3,603:
 
end.
</syntaxhighlight>
</lang>
 
Output:
Line 3,165 ⟶ 3,612:
=={{header|Perl}}==
 
<langsyntaxhighlight lang="perl">#! /usr/bin/perl
use strict;
my $trials = 10000;
Line 3,191 ⟶ 3,638:
 
print "Stay win ratio " . (100.0 * $stay/$trials) . "\n";
print "Switch win ratio " . (100.0 * $switch/$trials) . "\n";</langsyntaxhighlight>
 
=={{header|Phix}}==
Modified copy of [[Monty_Hall_problem#Euphoria|Euphoria]]
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">swapWins</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">stayWins</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">winner</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">choice</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">reveal</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">other</span>
Line 3,212 ⟶ 3,659:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Stay: %,d\nSwap: %,d\nTime: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">stayWins</span><span style="color: #0000FF;">,</span><span style="color: #000000;">swapWins</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)})</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,221 ⟶ 3,668:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
function montyhall($iterations){
$switch_win = 0;
Line 3,247 ⟶ 3,694:
montyhall(10000);
?></langsyntaxhighlight>
Output:
<pre>Iterations: 10000 - Stayed wins: 3331 (33.31%) - Switched wins: 6669 (66.69%)</pre>
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">go =>
_ = random2(), % different seed
member(Rounds,[1000,10_000,100_000,1_000_000,10_000_000]),
Line 3,280 ⟶ 3,727:
choice(N) = random(1,N).
 
pick(L) = L[random(1,L.len)].</langsyntaxhighlight>
 
{{out}}
Line 3,304 ⟶ 3,751:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de montyHall (Keep)
(let (Prize (rand 1 3) Choice (rand 1 3))
(if Keep # Keeping the first choice?
Line 3,322 ⟶ 3,769:
(do 10000 (and (montyHall NIL) (inc 'Cnt)))
(format Cnt 2) )
" %" )</langsyntaxhighlight>
Output:
<pre>Strategy KEEP -> 33.01 %
Line 3,329 ⟶ 3,776:
=={{header|PL/I}}==
{{trans|Java}}
<langsyntaxhighlight lang="pli">*process source attributes xref;
ziegen: Proc Options(main);
/* REXX ***************************************************************
Line 3,366 ⟶ 3,813:
Return(res);
End;
End;</langsyntaxhighlight>
Output:
<pre>
Line 3,376 ⟶ 3,823:
Use ghostscript or print this to a postscript printer
 
<syntaxhighlight lang="postscript">%!PS
<lang PostScript>%!PS
/Courier % name the desired font
20 selectfont % choose the size in points and establish
Line 3,411 ⟶ 3,858:
 
 
showpage % print all on the page</langsyntaxhighlight>
 
Sample output:
Line 3,420 ⟶ 3,867:
 
=={{header|PowerShell}}==
<langsyntaxhighlight Powershelllang="powershell">#Declaring variables
$intIterations = 10000
$intKept = 0
Line 3,473 ⟶ 3,920:
Write-Host "Keep : $intKept ($($intKept/$intIterations*100)%)"
Write-Host "Switch: $intSwitched ($($intSwitched/$intIterations*100)%)"
Write-Host ""</langsyntaxhighlight>
Output:
<pre>Results through 10000 iterations:
Line 3,481 ⟶ 3,928:
=={{header|Prolog}}==
{{works with|GNU Prolog}}
<syntaxhighlight lang="prolog">
<lang Prolog>
:- initialization(main).
 
Line 3,525 ⟶ 3,972:
win_count(1000, false, 0, StayTotal),
format('Staying wins ~d out of 1000.\n', [StayTotal]).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,531 ⟶ 3,978:
Staying wins 332 out of 1000.
</pre>
 
=={{header|PureBasic}}==
<lang PureBasic>Structure wins
stay.i
redecide.i
EndStructure
 
#goat = 0
#car = 1
Procedure MontyHall(*results.wins)
Dim Doors(2)
Doors(Random(2)) = #car
 
player = Random(2)
Select Doors(player)
Case #car
*results\redecide + #goat
*results\stay + #car
Case #goat
*results\redecide + #car
*results\stay + #goat
EndSelect
EndProcedure
OpenConsole()
#Tries = 1000000
Define results.wins
 
For i = 1 To #Tries
MontyHall(@results)
Next
PrintN("Trial runs for each option: " + Str(#Tries))
PrintN("Wins when redeciding: " + Str(results\redecide) + " (" + StrD(results\redecide / #Tries * 100, 2) + "% chance)")
PrintN("Wins when sticking: " + Str(results\stay) + " (" + StrD(results\stay / #Tries * 100, 2) + "% chance)")
Input()</lang>
 
Output:<pre>Trial runs for each option: 1000000
Wins when redeciding: 666459 (66.65% chance)
Wins when sticking: 333541 (33.35% chance)</pre>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">'''
I could understand the explanation of the Monty Hall problem
but needed some more evidence
Line 3,618 ⟶ 4,024:
print sum(monty_hall(randrange(3), switch=True)
for x in range(iterations)),
print "out of", iterations, "times.\n"</langsyntaxhighlight>
Sample output:
<pre>Monty Hall problem simulation:
Line 3,630 ⟶ 4,036:
===Python 3 version: ===
Another (simpler in my opinion), way to do this is below, also in python 3:
<langsyntaxhighlight lang="python">import random
#1 represents a car
#0 represent a goat
Line 3,662 ⟶ 4,068:
print("Stay =",stay)
print("Switch = ",switch)
#Done by Sam Witton 09/04/2014</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ $ "bigrat.qky" loadfile ] now!
[ 0 ( number of cars when not changing choice )
Line 3,683 ⟶ 4,089:
say "Approximate ratio of car wins with strategy A over strategy B: "
swap 100 round
vulgar$ echo$ cr ] is trials ( n --> )</langsyntaxhighlight>
 
{{out}}
Line 3,708 ⟶ 4,114:
=={{header|R}}==
 
<syntaxhighlight lang="rsplus">set.seed(19771025) # set the seed to set the same results as this code
<lang rsplus># Since R is a vector based language that penalizes for loops, we will avoid
# for-loops, instead using "apply" statement variants (like "map" in other
# functional languages).
 
set.seed(19771025) # set the seed to set the same results as this code
N <- 10000 # trials
true_answers <- sample(1:3, N, replace=TRUE)
Line 3,769 ⟶ 4,171:
change <- runif(N) >= .5
random_switch[change] <- other_door[change]
summary(random_switch == true_answers)</langsyntaxhighlight>
 
 
Line 3,835 ⟶ 4,237:
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 3,872 ⟶ 4,274:
 
(for-each test-strategy (list keep-choice change-choice))
</syntaxhighlight>
</lang>
 
Sample Output:
Line 3,885 ⟶ 4,287:
This implementation is parametric over the number of doors. [[wp:Monty_Hall_problem#Increasing_the_number_of_doors|Increasing the number of doors in play makes the superiority of the switch strategy even more obvious]].
 
<syntaxhighlight lang="raku" perl6line>enum Prize <Car Goat>;
enum Strategy <Stay Switch>;
Line 3,923 ⟶ 4,325:
'% of the time.'
}
}</langsyntaxhighlight>
{{out}}
<pre>With 3 doors:
Line 3,935 ⟶ 4,337:
===version 1===
{{trans|Java}}
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 30.08.2013 Walter Pachl derived from Java
**********************************************************************/
Line 3,965 ⟶ 4,367:
Say 'NetRexx:' time('E') 'seconds'
Exit
r3: Return random(2)+1</langsyntaxhighlight>
Output for 1000000 samples:
<pre>
Line 3,989 ⟶ 4,391:
 
===version 2===
<langsyntaxhighlight lang="rexx">/*REXX program simulates any number of trials of the classic TV show Monty Hall problem.*/
parse arg # seed . /*obtain the optional args from the CL.*/
if #=='' | #=="," then #= 1000000 /*Not specified? Then 1 million trials*/
Line 4,002 ⟶ 4,404:
say 'switching wins ' format(wins.0 / # * 100, , 1)"% of the time."
say ' staying wins ' format(wins.1 / # * 100, , 1)"% of the time." ; say
say 'performed ' # " times with 3 doors." /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 4,012 ⟶ 4,414:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
total = 10000
swapper = 0
Line 4,035 ⟶ 4,437:
see "the 'sticker' won " + sticker + " times (" + floor(sticker/total*100) + "%)" + nl
see "the 'swapper' won " + swapper + " times (" + floor(swapper/total*100) + "%)" + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,045 ⟶ 4,447:
=={{header|Ruby}}==
 
<langsyntaxhighlight lang="ruby">n = 10_000 #number of times to play
 
stay = switch = 0 #sum of each strategy's wins
Line 4,071 ⟶ 4,473:
 
puts "Staying wins %.2f%% of the time." % (100.0 * stay / n)
puts "Switching wins %.2f%% of the time." % (100.0 * switch / n)</langsyntaxhighlight>
Sample Output:
<pre>Staying wins 33.84% of the time.
Switching wins 66.16% of the time.</pre>
 
=={{header|Run BASIC}}==
<lang runbasic>' adapted from BASIC solution
 
input "Number of tries;";tries ' gimme the number of iterations
FOR plays = 1 TO tries
winner = INT(RND(1) * 3) + 1
doors(winner) = 1 'put a winner in a random door
choice = INT(RND(1) * 3) + 1 'pick a door please
[DO] shown = INT(RND(1) * 3) + 1
' ------------------------------------------
' don't show the winner or the choice
if doors(shown) = 1 then goto [DO]
if shown = choice then goto [DO]
if doors(choice) = 1 then
stayWins = stayWins + 1 ' if you won by staying, count it
else
switchWins = switchWins + 1 ' could have switched to win
end if
doors(winner) = 0 'clear the doors for the next test
NEXT
PRINT " Result for ";tries;" games."
PRINT "Switching wins ";switchWins; " times."
PRINT " Staying wins ";stayWins; " times."</lang>
 
=={{header|Rust}}==
{{libheader|rand}}
<langsyntaxhighlight lang="rust">extern crate rand;
use rand::Rng;
use rand::seq::SliceRandom;
Line 4,128 ⟶ 4,506:
percent = switch_wins as f64 / GAMES as f64 * 100.0
);
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">import scala.util.Random
 
object MontyHallSimulation {
Line 4,163 ⟶ 4,541:
switchStrategyWins, percent(switchStrategyWins)))
}
}</langsyntaxhighlight>
 
Sample:
Line 4,174 ⟶ 4,552:
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (random-from-list list) (list-ref list (random (length list))))
(define (random-permutation list)
(if (null? list)
Line 4,243 ⟶ 4,621:
;; > (compare-strategies 1000000)
;; (stay-strategy won with probability 33.3638 %
;; and switch-strategy won with probability 66.716 %)</langsyntaxhighlight>
 
=={{header|Scilab}}==
{{incorrect|scilab|Several syntax and logical errors: switch is a keyword, the variable a is never used, and in the result the sum does not yield 100000 (which is logical since both result are taken from different random samples, but they should not). Also some useless complexity: the nested if can be simplified with logical operators.}}
 
<syntaxhighlight lang="text">// How it works:
// MontyHall() is a function with argument switch:
// it will be called 100000 times with switch=%T,
Line 4,285 ⟶ 4,663:
end
disp("Switching, one wins"+ascii(10)+string(wins_switch)+" games out of "+string(games))
disp("Staying, one wins"+ascii(10)+string(wins_stay)+" games out of "+string(games))</langsyntaxhighlight>
 
Output:
Line 4,298 ⟶ 4,676:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 4,320 ⟶ 4,698:
writeln("Switching wins " <& switchWins <& " times");
writeln("Staying wins " <& stayWins <& " times");
end func;</langsyntaxhighlight>
 
Output:
Line 4,327 ⟶ 4,705:
Staying wins 3346 times
</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program monty_hall;
setrandom(0);
 
n_simulations := 100000;
print('Chance to win:');
print('When switching doors:', win_chance(true, n_simulations) * 100, '%');
print('When not switching doors:', win_chance(false, n_simulations) * 100, '%');
 
proc win_chance(switch, n_simulations);
wins := 0;
loop for i in [1..n_simulations] do
wins +:= if simulate(switch) then 1 else 0 end;
end loop;
return wins / n_simulations;
end proc;
 
proc simulate(switch);
doors := {1, 2, 3};
car := random doors;
goats := doors less car;
choice := random doors;
opened := random (goats less choice);
 
if switch then
choice := arb (doors less choice less opened);
end if;
return choice = car;
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>Chance to win:
When switching doors: 66.584 %
When not switching doors: 33.093 %</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var n = 1000 # number of times to play
var switchWins = (var stayWins = 0) # sum of each strategy's wins
 
Line 4,349 ⟶ 4,762:
 
say ("Staying wins %.2f%% of the time." % (100.0 * stayWins / n))
say ("Switching wins %.2f%% of the time." % (100.0 * switchWins / n))</langsyntaxhighlight>
{{out}}
<pre>
Line 4,358 ⟶ 4,771:
=={{header|SPAD}}==
{{works with|FriCAS, OpenAxiom, Axiom}}
<syntaxhighlight lang="spad">
<lang SPAD>
montyHall(n) ==
wd:=[1+random(3) for j in 1..n]
Line 4,365 ⟶ 4,778:
p:=(st/n)::DoubleFloat
FORMAT(nil,"stay: ~A, switch: ~A",p,1-p)$Lisp
</syntaxhighlight>
</lang>
Domain:[http://fricas.github.io/api/Integer.html?highlight=random Integer]
 
Line 4,384 ⟶ 4,797:
(3) stay: 0.33526, switch: 0.66474
Type: SExpression
</pre>
 
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "monty" )
@( description, "Run random simulations of the Monty Hall game. Show the" )
@( description, "effects of a strategy of the contestant always keeping" )
@( description, "his first guess so it can be contrasted with the" )
@( description, "strategy of the contestant always switching his guess." )
@( description, "Simulate at least a thousand games using three doors" )
@( description, "for each strategy and show the results in such a way as" )
@( description, "to make it easy to compare the effects of each strategy." )
@( see_also, "http://rosettacode.org/wiki/Monty_Hall_problem" )
@( author, "Ken O. Burtch" );
pragma license( unrestricted );
 
pragma restriction( no_external_commands );
 
procedure monty is
num_iterations : constant positive := 100_000;
type action_type is (stay, switch);
type prize_type is (goat, pig, car);
doors : array(1..3) of prize_type;
type door_index is new positive;
 
-- place the prizes behind random doors
 
procedure set_prizes is
begin
doors( 1 ) := goat;
doors( 2 ) := pig;
doors( 3 ) := car;
arrays.shuffle( doors );
end set_prizes;
 
-- determine if the prize was chosen based on strategy
 
function play( action : action_type ) return prize_type is
chosen : door_index := door_index( numerics.rnd(3) );
monty : door_index;
begin
set_prizes;
for i in arrays.first(doors)..arrays.last(doors) loop
if i /= chosen and doors(i) /= car then
monty := i;
end if;
end loop;
if action = switch then
for i in arrays.first(doors)..arrays.last(doors) loop
if i /= monty and i /= chosen then
chosen := i;
exit;
end if;
end loop;
end if;
return doors( chosen );
end play;
 
winners : natural; -- times won
pct : float; -- percentage won
 
begin
winners := 0;
for i in 1..num_iterations loop
if play( stay ) = car then
winners := @+1;
end if;
end loop;
pct := float( winners * 100 ) / float( num_iterations );
put( "Stay: count" ) @ ( winners ) @ ( " = " ) @ ( pct ) @ ( "%" );
new_line;
winners := 0;
for i in 1..num_iterations loop
if play( switch ) = car then
winners := @+1;
end if;
end loop;
pct := float( winners * 100 ) / float( num_iterations );
put( "Switch: count" ) @ ( winners ) @ ( " = " ) @ ( pct ) @ ( "%" );
new_line;
end monty;</syntaxhighlight>
 
=={{header|Standard ML}}==
Works with SML/NJ or with MLton using the SML/NJ Util library.
 
<syntaxhighlight lang="standard ml">
val pidint = Word64.toInt(Posix.Process.pidToWord(Posix.ProcEnv.getpid()));
val rand = Random.rand(LargeInt.toInt(Time.toSeconds(Time.now())), pidint);
 
fun stick_win 0 wins = wins
| stick_win trial wins =
let
val winner_door = (Random.randNat rand) mod 3;
val chosen_door = (Random.randNat rand) mod 3;
in
if winner_door = chosen_door then
stick_win (trial-1) (wins+1)
else
stick_win (trial-1) wins
end
 
val trials = 1000000;
val sticks = stick_win trials 0;
val stick_winrate = 100.0 * Real.fromInt(sticks) / Real.fromInt(trials);
(* if you lost by sticking you would have won by swapping *)
val swap_winrate = 100.0 - stick_winrate;
 
(print ("sticking = " ^ Real.toString(stick_winrate) ^ "% win rate\n");
print ("swapping = " ^ Real.toString(swap_winrate) ^ "% win rate\n"));
</syntaxhighlight>
 
'''Output'''
<pre>
sticking = 33.3449% win rate
swapping = 66.6551% win rate
</pre>
 
=={{header|Stata}}==
 
<langsyntaxhighlight lang="stata">clear
set obs 1000000
gen car=runiformint(1,3)
Line 4,397 ⟶ 4,926:
gen choice2=6-shown-choice1
gen succ2=car==choice2
tabstat succ1 succ2, s(mean)</langsyntaxhighlight>
 
'''Output'''
Line 4,408 ⟶ 4,937:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">import Foundation
 
func montyHall(doors: Int = 3, guess: Int, switch: Bool) -> Bool {
Line 4,430 ⟶ 4,959:
 
print("Switching would've won \((Double(switchWins) / Double(switchResults.count)) * 100)% of games")
print("Not switching would've won \(((Double(switchResults.count - switchWins)) / Double(switchResults.count)) * 100)% of games")</langsyntaxhighlight>
 
{{out}}
Line 4,438 ⟶ 4,967:
=={{header|Tcl}}==
A simple way of dealing with this one, based on knowledge of the underlying probabilistic system, is to use code like this:
<langsyntaxhighlight lang="tcl">set stay 0; set change 0; set total 10000
for {set i 0} {$i<$total} {incr i} {
if {int(rand()*3) == int(rand()*3)} {
Line 4,447 ⟶ 4,976:
}
puts "Estimate: $stay/$total wins for staying strategy"
puts "Estimate: $change/$total wins for changing strategy"</langsyntaxhighlight>
But that's not really the point of this challenge; it should add the concealing factors too so that we're simulating not just the solution to the game, but also the game itself. (Note that we are using Tcl's lists here to simulate sets.)
 
We include a third strategy that is proposed by some people (who haven't thought much about it) for this game: just picking at random between all the doors offered by Monty the second time round.
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
# Utility: pick a random item from a list
Line 4,516 ⟶ 5,045:
puts "Estimate: $stay/$total wins for 'staying' strategy"
puts "Estimate: $change/$total wins for 'changing' strategy"
puts "Estimate: $anew/$total wins for 'picking anew' strategy"</langsyntaxhighlight>
This might then produce output like
Estimate: 3340/10000 wins for 'staying' strategy
Line 4,525 ⟶ 5,054:
=={{header|Transact SQL}}==
T-SQL for general case:
<syntaxhighlight lang="transact sql">
<lang Transact SQL>
---- BEGIN ------------
create table MONTY_HALL(
Line 4,567 ⟶ 5,096:
from MONTY_HALL
---- END ------------
</syntaxhighlight>
</lang>
<pre>
% OF WINS FOR KEEP % OF WINS FOR CHANGE % OF WINS FOR RANDOM
Line 4,576 ⟶ 5,105:
=={{header|UNIX Shell}}==
{{works with|bash|2.x| and most bash-compatible unix shells}}
<langsyntaxhighlight lang="bash">#!/bin/bash
# Simulates the "monty hall" probability paradox and shows results.
# http://en.wikipedia.org/wiki/Monty_Hall_problem
Line 4,647 ⟶ 5,176:
echo "Wins (switch to remaining door): $num_win"
echo "Losses (first guess was correct): $num_lose"
exit 0</langsyntaxhighlight>
Output of a few runs:
<pre>
Line 4,701 ⟶ 5,230:
for the switching strategy.
 
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
#import flo
Line 4,717 ⟶ 5,246:
#show+
 
main = ~&plrTS/<'stay: ','switch: '> format* <staying_wins,switching_wins></langsyntaxhighlight>
Output will vary slightly for each run due to randomness.
<pre>
Line 4,725 ⟶ 5,254:
 
=={{header|Vedit macro language}}==
{{trans|BASICQuickBASIC}}
 
Vedit macro language does not have random number generator, so one is implemented in subroutine RANDOM (the algorithm was taken from ANSI C library).
<langsyntaxhighlight lang="vedit">#90 = Time_Tick // seed for random number generator
#91 = 3 // random numbers in range 0 to 2
#1 = 0 // wins for "always stay" strategy
Line 4,761 ⟶ 5,290:
#93 = 0x7fffffff % 48271
#90 = (48271 * (#90 % #92) - #93 * (#90 / #92)) & 0x7fffffff
return ((#90 & 0xffff) * #91 / 0x10000)</langsyntaxhighlight>
 
Sample output:
Line 4,767 ⟶ 5,296:
Staying winns: 3354
Switching winns: 6646
</pre>
 
=={{header|V (Vlang)}}==
{{trans|Java}}
<syntaxhighlight lang="v (vlang)">
import rand
 
fn main() {
games := 1_000_000
mut doors := [3]int{}
mut switch_wins, mut stay_wins, mut shown, mut guess := 0, 0, 0, 0
for _ in 1..games + 1 {
doors[rand.int_in_range(0, 3) or {exit(1)}] = 1 // Set which one has the car
guess = rand.int_in_range(0, 3) or {exit(1)} // Choose a door
for doors[shown] == 1 || shown == guess {
shown = rand.int_in_range(0, 3) or {exit(1)} // Shown door
}
stay_wins += doors[guess]
switch_wins += doors[3 - guess - shown]
for clear in 0..3 {if doors[clear] != 0 {doors[clear] = 0}}
}
println("Simulating ${games} games:")
println("Staying wins ${stay_wins} times at ${(f32(stay_wins) / f32(games) * 100):.2}% of games")
println("Switching wins ${switch_wins} times at ${(f32(switch_wins) / f32(games) * 100):.2}% of games")
}
</syntaxhighlight>
 
{{out}}
<pre>
Simulating 1000000 games:
Staying wins 332518 times at 33.25% of games
Switching wins 667482 times at 66.75% of games
</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
<langsyntaxhighlight ecmascriptlang="wren">import "random" for Random
 
var montyHall = Fn.new { |games|
Line 4,794 ⟶ 5,355:
}
 
montyHall.call(1e6)</langsyntaxhighlight>
 
{{out}}
Line 4,805 ⟶ 5,366:
 
=={{header|X++}}==
<langsyntaxhighlight lang="x++">//Evidence of the Monty Hall solution in Dynamics AX (by Wessel du Plooy - HiGH Software).
 
int changeWins = 0;
Line 4,838 ⟶ 5,399:
print strFmt("Staying wins %1 times.", noChangeWins);
pause;
</syntaxhighlight>
</lang>
 
Output:
Line 4,845 ⟶ 5,406:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">def GamesNGames = 10000; \number of games simulated
int Game, WinsNWins;
include c:\cxpl\codes;
 
procfunc Playint IsGameWon(Switch); \Play one game
int Switch;
int Car, Player, Player0, Monty;
Line 4,860 ⟶ 5,421:
until Player # Player0 and Player # Monty
else Player:= Player0; \player sticks with original door
ifreturn Player = Car then Wins:= Wins+1;
];
 
[Format(2,1);
NWins:= 0;
Text(0, "Not switching doors wins car in ");
for Game:= 0 to NGames-1 do
Wins:= 0;
if IsGameWon(false) then NWins:= NWins+1;
for Game:= 0 to Games-1 do Play(false);
Text(0, "NOT switching doors wins car in ");
RlOut(0, float(Wins)/float(Games)*100.0);
RlOut(0, float(NWins)/float(NGames)*100.0);
Text(0, "% of games.^M^J");
 
NWins:= 0;
for Game:= 0 to NGames-1 do
if IsGameWon(true) then NWins:= NWins+1;
Text(0, "But switching doors wins car in ");
RlOut(0, float(NWins)/float(NGames)*100.0);
Wins:= 0;
for Game:= 0 to Games-1 do Play(true);
RlOut(0, float(Wins)/float(Games)*100.0);
Text(0, "% of games.^M^J");
]</langsyntaxhighlight>
 
Example output:
<pre>
NotNOT switching doors wins car in 33.7% of games.
But switching doors wins car in 66.7% of games.
</pre>
 
=={{header|Zig}}==
<syntaxhighlight lang="zig">const std = @import("std");
 
const number_of_simulations: u32 = 10_000_000;
=={{header|Yabasic}}==
<lang yabasic>
numTiradas = 1000000
 
pub fn main() !void {
for i = 1 to numTiradas
var stick_wins: u32 = 0;
pta_coche = int(ran(3)) + 1
var switch_wins: u32 = 0;
pta_elegida = int(ran(3)) + 1
var doors = [3]bool{ true, false, false };
if pta_coche <> pta_elegida then
pta_montys = 6 - pta_coche - pta_elegida
else
repeat
pta_montys = int(ran(3)) + 1
until pta_montys <> pta_coche
end if
// manteenr elección
if pta_coche = pta_elegida then permanece = permanece + 1 : fi
// cambiar elección
if pta_coche = 6 - pta_montys - pta_elegida then cambia = cambia + 1 : fi
next i
 
var t = std.rand.DefaultPrng.init(42);
print "Si mantiene su eleccion, tiene un ", permanece / numTiradas * 100, "% de probabilidades de ganar."
const r = t.random();
print "Si cambia, tiene un ", cambia / numTiradas * 100, "% de probabilidades de ganar."
 
end
var guess: u8 = undefined;
</lang>
var door_shown: u8 = undefined;
 
for (0..number_of_simulations) |_| {
std.rand.Random.shuffle(r, bool, &doors);
guess = r.intRangeAtMost(u8, 0, 2);
door_shown = r.intRangeAtMost(u8, 0, 2);
while (!doors[door_shown] and door_shown != guess) door_shown = r.intRangeAtMost(u8, 0, 2);
if (doors[guess]) {
stick_wins += 1;
} else {
switch_wins += 1;
}
}
 
std.debug.print("After {} simulations:\nStick wins: {}\nSwitch wins: {}\n", .{ number_of_simulations, stick_wins, switch_wins });
}</syntaxhighlight>
 
 
=={{header|zkl}}==
{{trans|Go}}
<langsyntaxhighlight lang="zkl">const games=0d100_000;
 
reg switcherWins=0, keeperWins=0, shown=0;
Line 4,928 ⟶ 5,496:
switcherWins, switcherWins.toFloat() / games * 100).println();
"Keeper Wins: %,d (%3.2f%%)".fmt(
keeperWins, keeperWins.toFloat() / games * 100).println();</langsyntaxhighlight>
{{out}}
<pre>
2,122

edits