Monty Hall problem: Difference between revisions
Content added Content deleted
m (→{{header|R}}: nonsense: apply functions are not faster than a for loop, they have basically the same problem: not vectorized, i.e. one function call per element.) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 47: | Line 47: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">V stay = 0 |
||
V sw = 0 |
V sw = 0 |
||
Line 71: | Line 71: | ||
print(‘Stay = ’stay) |
print(‘Stay = ’stay) |
||
print(‘Switch = ’sw)</ |
print(‘Switch = ’sw)</syntaxhighlight> |
||
=={{header|8086 Assembly}}== |
=={{header|8086 Assembly}}== |
||
< |
<syntaxhighlight lang="asm">time: equ 2Ch ; MS-DOS syscall to get current time |
||
puts: equ 9 ; MS-DOS syscall to print a string |
puts: equ 9 ; MS-DOS syscall to print a string |
||
cpu 8086 |
cpu 8086 |
||
Line 153: | Line 153: | ||
nsw: db 'When not switching doors: $' |
nsw: db 'When not switching doors: $' |
||
db '*****' |
db '*****' |
||
number: db 13,10,'$'</ |
number: db 13,10,'$'</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 161: | Line 161: | ||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
< |
<syntaxhighlight lang="actionscript">package { |
||
import flash.display.Sprite; |
import flash.display.Sprite; |
||
Line 192: | Line 192: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>Switching wins 18788 times. (62.626666666666665%) |
<pre>Switching wins 18788 times. (62.626666666666665%) |
||
Line 198: | Line 198: | ||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang="ada">-- Monty Hall Game |
||
with Ada.Text_Io; use Ada.Text_Io; |
with Ada.Text_Io; use Ada.Text_Io; |
||
Line 273: | Line 273: | ||
Put_Line("%"); |
Put_Line("%"); |
||
end Monty_Stats;</ |
end Monty_Stats;</syntaxhighlight> |
||
Results |
Results |
||
<pre>Stay : count 34308 = 34.31% |
<pre>Stay : count 34308 = 34.31% |
||
Line 284: | Line 284: | ||
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}} |
{{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}} |
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}} |
||
< |
<syntaxhighlight lang="algol68">INT trials=100 000; |
||
PROC brand = (INT n)INT: 1 + ENTIER (n * random); |
PROC brand = (INT n)INT: 1 + ENTIER (n * random); |
||
Line 337: | Line 337: | ||
print(("Changing: ", percent(change winning), new line )); |
print(("Changing: ", percent(change winning), new line )); |
||
print(("New random choice: ", percent(random winning), new line )) |
print(("New random choice: ", percent(random winning), new line )) |
||
)</ |
)</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
<pre> |
<pre> |
||
Line 346: | Line 346: | ||
=={{header|APL}}== |
=={{header|APL}}== |
||
< |
<syntaxhighlight lang="apl"> ∇ Run runs;doors;i;chosen;cars;goats;swap;stay;ix;prices |
||
[1] ⍝0: Monthy Hall problem |
[1] ⍝0: Monthy Hall problem |
||
[2] ⍝1: http://rosettacode.org/wiki/Monty_Hall_problem |
[2] ⍝1: http://rosettacode.org/wiki/Monty_Hall_problem |
||
Line 360: | Line 360: | ||
[12] ⎕←'Swap: ',(2⍕100×(swap÷runs)),'% it''s a car' |
[12] ⎕←'Swap: ',(2⍕100×(swap÷runs)),'% it''s a car' |
||
[13] ⎕←'Stay: ',(2⍕100×(stay÷runs)),'% it''s a car' |
[13] ⎕←'Stay: ',(2⍕100×(stay÷runs)),'% it''s a car' |
||
∇</ |
∇</syntaxhighlight> |
||
<pre> |
<pre> |
||
Run 100000 |
Run 100000 |
||
Line 371: | Line 371: | ||
{{trans|Nim}} |
{{trans|Nim}} |
||
< |
<syntaxhighlight lang="rebol">stay: 0 |
||
swit: 0 |
swit: 0 |
||
Line 394: | Line 394: | ||
print ["Stay:" stay] |
print ["Stay:" stay] |
||
print ["Switch:" swit]</ |
print ["Switch:" swit]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 402: | Line 402: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="ahk">#SingleInstance, Force |
||
Iterations = 1000 |
Iterations = 1000 |
||
Loop, %Iterations% |
Loop, %Iterations% |
||
Line 435: | Line 435: | ||
Mode := Mode = 2 ? 2*rand - 1: Mode |
Mode := Mode = 2 ? 2*rand - 1: Mode |
||
Return, Mode = 1 ? 6 - guess - show = actual : guess = actual |
Return, Mode = 1 ? 6 - guess - show = actual : guess = actual |
||
}</ |
}</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
<pre> |
<pre> |
||
Line 448: | Line 448: | ||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
< |
<syntaxhighlight lang="awk">#!/bin/gawk -f |
||
# Monty Hall problem |
# Monty Hall problem |
||
Line 504: | Line 504: | ||
simulate(RAND) |
simulate(RAND) |
||
}</ |
}</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
< |
<syntaxhighlight lang="awk">bash$ ./monty_hall.awk |
||
Monty Hall problem simulation: |
Monty Hall problem simulation: |
||
Line 514: | Line 514: | ||
Algorithm switch: prize count = 6655, = 66.55% |
Algorithm switch: prize count = 6655, = 66.55% |
||
Algorithm random: prize count = 4991, = 49.91% |
Algorithm random: prize count = 4991, = 49.91% |
||
bash$</ |
bash$</syntaxhighlight> |
||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
{{works with|QuickBasic|4.5}} |
{{works with|QuickBasic|4.5}} |
||
{{trans|Java}} |
{{trans|Java}} |
||
< |
<syntaxhighlight lang="qbasic">RANDOMIZE TIMER |
||
DIM doors(3) '0 is a goat, 1 is a car |
DIM doors(3) '0 is a goat, 1 is a car |
||
CLS |
CLS |
||
Line 537: | Line 537: | ||
NEXT plays |
NEXT plays |
||
PRINT "Switching wins"; switchWins; "times." |
PRINT "Switching wins"; switchWins; "times." |
||
PRINT "Staying wins"; stayWins; "times."</ |
PRINT "Staying wins"; stayWins; "times."</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>Switching wins 21805 times. |
<pre>Switching wins 21805 times. |
||
Line 544: | Line 544: | ||
==={{header|BASIC256}}=== |
==={{header|BASIC256}}=== |
||
<syntaxhighlight lang="basic256"> |
|||
<lang BASIC256> |
|||
numTiradas = 1000000 |
numTiradas = 1000000 |
||
permanece = 0 |
permanece = 0 |
||
Line 568: | Line 568: | ||
print "Si cambia, tiene un "; cambia / numTiradas * 100; "% de probabilidades de ganar." |
print "Si cambia, tiene un "; cambia / numTiradas * 100; "% de probabilidades de ganar." |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|IS-BASIC}}=== |
==={{header|IS-BASIC}}=== |
||
< |
<syntaxhighlight lang="is-basic">100 PROGRAM "MontyH.bas" |
||
110 RANDOMIZE |
110 RANDOMIZE |
||
120 LET NUMGAMES=1000 |
120 LET NUMGAMES=1000 |
||
Line 585: | Line 585: | ||
220 PRINT "Num of games:";NUMGAMES |
220 PRINT "Num of games:";NUMGAMES |
||
230 PRINT "Wins not changing doors:";NOTCHANGING,NOTCHANGING/NUMGAMES*100;"% of total." |
230 PRINT "Wins not changing doors:";NOTCHANGING,NOTCHANGING/NUMGAMES*100;"% of total." |
||
240 PRINT "Wins changing doors:",CHANGING,CHANGING/NUMGAMES*100;"% of total."</ |
240 PRINT "Wins changing doors:",CHANGING,CHANGING/NUMGAMES*100;"% of total."</syntaxhighlight> |
||
==={{header|Sinclair ZX81 BASIC}}=== |
==={{header|Sinclair ZX81 BASIC}}=== |
||
Line 596: | Line 596: | ||
switcher wins;</pre> |
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. |
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. |
||
< |
<syntaxhighlight lang="basic"> 10 PRINT " WINS IF YOU" |
||
20 PRINT "STICK","SWITCH" |
20 PRINT "STICK","SWITCH" |
||
30 LET STICK=0 |
30 LET STICK=0 |
||
Line 610: | Line 610: | ||
130 IF NEWGUESS=CAR THEN LET SWITCH=SWITCH+1 |
130 IF NEWGUESS=CAR THEN LET SWITCH=SWITCH+1 |
||
140 NEXT I |
140 NEXT I |
||
150 PRINT AT 2,0;STICK,SWITCH</ |
150 PRINT AT 2,0;STICK,SWITCH</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> WINS IF YOU |
<pre> WINS IF YOU |
||
Line 618: | Line 618: | ||
==={{header|True BASIC}}=== |
==={{header|True BASIC}}=== |
||
< |
<syntaxhighlight lang="basic"> |
||
LET numTiradas = 1000000 |
LET numTiradas = 1000000 |
||
Line 640: | Line 640: | ||
PRINT "Mantenerse gana el"; cambia / numTiradas * 100; "% de las veces." |
PRINT "Mantenerse gana el"; cambia / numTiradas * 100; "% de las veces." |
||
END |
END |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
< |
<syntaxhighlight lang="bbcbasic"> total% = 10000 |
||
FOR trial% = 1 TO total% |
FOR trial% = 1 TO total% |
||
prize_door% = RND(3) : REM. The prize is behind this door |
prize_door% = RND(3) : REM. The prize is behind this door |
||
Line 664: | Line 664: | ||
PRINT "After a total of ";total%;" trials," |
PRINT "After a total of ";total%;" trials," |
||
PRINT "The 'sticker' won ";sticker%;" times (";INT(sticker%/total%*100);"%)" |
PRINT "The 'sticker' won ";sticker%;" times (";INT(sticker%/total%*100);"%)" |
||
PRINT "The 'swapper' won ";swapper%;" times (";INT(swapper%/total%*100);"%)"</ |
PRINT "The 'swapper' won ";swapper%;" times (";INT(swapper%/total%*100);"%)"</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 674: | Line 674: | ||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">//Evidence of the Monty Hall solution. |
||
#include <stdio.h> |
#include <stdio.h> |
||
Line 697: | Line 697: | ||
printf("\nAfter %u games, I won %u by switching. That is %f%%. ", GAMES, winsbyswitch, (float)winsbyswitch*100.0/(float)i); |
printf("\nAfter %u games, I won %u by switching. That is %f%%. ", GAMES, winsbyswitch, (float)winsbyswitch*100.0/(float)i); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output of one run: |
Output of one run: |
||
Line 705: | Line 705: | ||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
{{trans|Java}} |
{{trans|Java}} |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
class Program |
class Program |
||
Line 740: | Line 740: | ||
Console.Out.WriteLine("Switching wins " + switchWins + " times."); |
Console.Out.WriteLine("Switching wins " + switchWins + " times."); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
<pre> |
<pre> |
||
Line 748: | Line 748: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <cstdlib> |
#include <cstdlib> |
||
#include <ctime> |
#include <ctime> |
||
Line 804: | Line 804: | ||
int wins_change = check(games, true); |
int wins_change = check(games, true); |
||
std::cout << "staying: " << 100.0*wins_stay/games << "%, changing: " << 100.0*wins_change/games << "%\n"; |
std::cout << "staying: " << 100.0*wins_stay/games << "%, changing: " << 100.0*wins_change/games << "%\n"; |
||
}</ |
}</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
staying: 33.73%, changing: 66.9% |
staying: 33.73%, changing: 66.9% |
||
=={{header|Chapel}}== |
=={{header|Chapel}}== |
||
< |
<syntaxhighlight lang="chapel">use Random; |
||
param doors: int = 3; |
param doors: int = 3; |
||
Line 860: | Line 860: | ||
writeln( "Both methods are equal." ); |
writeln( "Both methods are equal." ); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Sample output: |
Sample output: |
||
<pre> |
<pre> |
||
Line 869: | Line 869: | ||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="clojure">(ns monty-hall-problem |
||
(:use [clojure.contrib.seq :only (shuffle)])) |
(:use [clojure.contrib.seq :only (shuffle)])) |
||
Line 884: | Line 884: | ||
(range times))] |
(range times))] |
||
(str "wins " wins " times out of " times))) |
(str "wins " wins " times out of " times))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang="clojure">monty-hall-problem> (println "staying:" (simulate true 1000)) |
||
staying: wins 337 times out of 1000 |
staying: wins 337 times out of 1000 |
||
nil |
nil |
||
Line 891: | Line 891: | ||
switching: wins 638 times out of 1000 |
switching: wins 638 times out of 1000 |
||
nil |
nil |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
{{works with|OpenCOBOL}} |
{{works with|OpenCOBOL}} |
||
< |
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION. |
||
PROGRAM-ID. monty-hall. |
PROGRAM-ID. monty-hall. |
||
Line 983: | Line 983: | ||
END PROGRAM get-rand-int. |
END PROGRAM get-rand-int. |
||
END PROGRAM monty-hall.</ |
END PROGRAM monty-hall.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 992: | Line 992: | ||
=={{header|ColdFusion}}== |
=={{header|ColdFusion}}== |
||
< |
<syntaxhighlight lang="cfm"><cfscript> |
||
function runmontyhall(num_tests) { |
function runmontyhall(num_tests) { |
||
// number of wins when player switches after original selection |
// number of wins when player switches after original selection |
||
Line 1,033: | Line 1,033: | ||
} |
} |
||
runmontyhall(10000); |
runmontyhall(10000); |
||
</cfscript></ |
</cfscript></syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,040: | Line 1,040: | ||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defun make-round () |
||
(let ((array (make-array 3 |
(let ((array (make-array 3 |
||
:element-type 'bit |
:element-type 'bit |
||
Line 1,054: | Line 1,054: | ||
(defun won? (array i) |
(defun won? (array i) |
||
(= 1 (bit array i)))</ |
(= 1 (bit array i)))</syntaxhighlight> |
||
< |
<syntaxhighlight lang="lisp">CL-USER> (progn (loop repeat #1=(expt 10 6) |
||
for round = (make-round) |
for round = (make-round) |
||
for initial = (random 3) |
for initial = (random 3) |
||
Line 1,072: | Line 1,072: | ||
#1# 1/100)))))) |
#1# 1/100)))))) |
||
Stay: 33.2716% |
Stay: 33.2716% |
||
Switch: 66.6593%</ |
Switch: 66.6593%</syntaxhighlight> |
||
< |
<syntaxhighlight lang="lisp"> |
||
;Find out how often we win if we always switch |
;Find out how often we win if we always switch |
||
(defun rand-elt (s) |
(defun rand-elt (s) |
||
Line 1,089: | Line 1,089: | ||
(defun monty-trials (n) |
(defun monty-trials (n) |
||
(count t (loop for x from 1 to n collect (monty)))) |
(count t (loop for x from 1 to n collect (monty)))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.random; |
||
void main() { |
void main() { |
||
Line 1,122: | Line 1,122: | ||
writefln("Switching/Staying wins: %d %d", switchWins, stayWins); |
writefln("Switching/Staying wins: %d %d", switchWins, stayWins); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Switching/Staying wins: 66609 33391</pre> |
<pre>Switching/Staying wins: 66609 33391</pre> |
||
Line 1,128: | Line 1,128: | ||
=={{header|Dart}}== |
=={{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. |
The class Game attempts to hide the implementation as much as possible, the play() function does not use any specifics of the implementation. |
||
< |
<syntaxhighlight lang="dart">int rand(int max) => (Math.random()*max).toInt(); |
||
class Game { |
class Game { |
||
Line 1,210: | Line 1,210: | ||
play(10000,false); |
play(10000,false); |
||
play(10000,true); |
play(10000,true); |
||
}</ |
}</syntaxhighlight> |
||
<pre>playing without switching won 33.32% |
<pre>playing without switching won 33.32% |
||
playing with switching won 67.63%</pre> |
playing with switching won 67.63%</pre> |
||
Line 1,218: | Line 1,218: | ||
{{works with|Delphi|XE10}} |
{{works with|Delphi|XE10}} |
||
{{libheader| System.SysUtils}} |
{{libheader| System.SysUtils}} |
||
< |
<syntaxhighlight lang="delphi">program MontyHall; |
||
{$APPTYPE CONSOLE} |
{$APPTYPE CONSOLE} |
||
Line 1,267: | Line 1,267: | ||
WriteLn('Switching wins ' + IntToStr(switchWins) + ' times.'); |
WriteLn('Switching wins ' + IntToStr(switchWins) + ' times.'); |
||
end. |
end. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>Staying wins 333253 times. |
<pre>Staying wins 333253 times. |
||
Line 1,276: | Line 1,276: | ||
{{trans|C#}} |
{{trans|C#}} |
||
< |
<syntaxhighlight lang="dyalect">var switchWins = 0 |
||
var stayWins = 0 |
var stayWins = 0 |
||
Line 1,295: | Line 1,295: | ||
print("Staying wins \(stayWins) times.") |
print("Staying wins \(stayWins) times.") |
||
print("Switching wins \(switchWins) times.")</ |
print("Switching wins \(switchWins) times.")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,303: | Line 1,303: | ||
=={{header|Eiffel}}== |
=={{header|Eiffel}}== |
||
< |
<syntaxhighlight lang="eiffel"> |
||
note |
note |
||
description: "[ |
description: "[ |
||
Line 1,617: | Line 1,617: | ||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,637: | Line 1,637: | ||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<syntaxhighlight lang="elixir">defmodule MontyHall do |
||
def simulate(n) do |
def simulate(n) do |
||
{stay, switch} = simulate(n, 0, 0) |
{stay, switch} = simulate(n, 0, 0) |
||
Line 1,659: | Line 1,659: | ||
end |
end |
||
MontyHall.simulate(10000)</ |
MontyHall.simulate(10000)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,669: | Line 1,669: | ||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
{{trans|Picolisp}} |
{{trans|Picolisp}} |
||
< |
<syntaxhighlight lang="lisp">(defun montyhall (keep) |
||
(let ((prize (random 3)) |
(let ((prize (random 3)) |
||
(choice (random 3))) |
(choice (random 3))) |
||
Line 1,683: | Line 1,683: | ||
(dotimes (i 10000) |
(dotimes (i 10000) |
||
(and (montyhall nil) (setq cnt (1+ cnt)))) |
(and (montyhall nil) (setq cnt (1+ cnt)))) |
||
(message "Strategy switch: %.3f%%" (/ cnt 100.0)))</ |
(message "Strategy switch: %.3f%%" (/ cnt 100.0)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,691: | Line 1,691: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang="erlang">-module(monty_hall). |
||
-export([main/0]). |
-export([main/0]). |
||
Line 1,718: | Line 1,718: | ||
false -> OpenDoor |
false -> OpenDoor |
||
end. |
end. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Sample Output: |
Sample Output: |
||
<pre>Switching wins 66595 times. |
<pre>Switching wins 66595 times. |
||
Line 1,724: | Line 1,724: | ||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang="euphoria">integer switchWins, stayWins |
||
switchWins = 0 |
switchWins = 0 |
||
stayWins = 0 |
stayWins = 0 |
||
Line 1,744: | Line 1,744: | ||
printf(1, "Switching wins %d times\n", switchWins) |
printf(1, "Switching wins %d times\n", switchWins) |
||
printf(1, "Staying wins %d times\n", stayWins) |
printf(1, "Staying wins %d times\n", stayWins) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Sample Output:<br /> |
Sample Output:<br /> |
||
:Switching wins 6697 times<br /> |
:Switching wins 6697 times<br /> |
||
Line 1,751: | Line 1,751: | ||
=={{header|F_Sharp|F#}}== |
=={{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. |
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. |
||
< |
<syntaxhighlight lang="fsharp">open System |
||
let monty nSims = |
let monty nSims = |
||
let rnd = new Random() |
let rnd = new Random() |
||
Line 1,763: | Line 1,763: | ||
let Wins (f:unit -> int) = seq {for i in [1..nSims] -> f()} |> Seq.sum |
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</ |
printfn "Stay: %d wins out of %d - Switch: %d wins out of %d" (Wins StayGame) nSims (Wins SwitchGame) nSims</syntaxhighlight> |
||
Sample Output: |
Sample Output: |
||
<pre>Stay: 332874 wins out of 1000000 - Switch: 667369 wins out of 1000000</pre> |
<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... |
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... |
||
< |
<syntaxhighlight lang="fsharp">let montySlower nSims = |
||
let rnd = new Random() |
let rnd = new Random() |
||
let MontyPick winner pick = |
let MontyPick winner pick = |
||
Line 1,799: | Line 1,799: | ||
let Wins (f:unit -> int) = seq {for i in [1..nSims] -> f()} |> Seq.sum |
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</ |
printfn "Stay: %d wins out of %d - Switch: %d wins out of %d" (Wins StayGame) nSims (Wins SwitchGame) nSims</syntaxhighlight> |
||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
===version 1=== |
===version 1=== |
||
< |
<syntaxhighlight lang="forth">include random.fs |
||
variable stay-wins |
variable stay-wins |
||
Line 1,820: | Line 1,820: | ||
cr switch-wins @ . [char] / emit . ." switching wins" ; |
cr switch-wins @ . [char] / emit . ." switching wins" ; |
||
1000 trials</ |
1000 trials</syntaxhighlight> |
||
or in iForth: |
or in iForth: |
||
< |
<syntaxhighlight lang="forth">0 value stay-wins |
||
0 value switch-wins |
0 value switch-wins |
||
Line 1,837: | Line 1,837: | ||
dup 0 ?DO trial LOOP |
dup 0 ?DO trial LOOP |
||
CR stay-wins DEC. ." / " dup DEC. ." staying wins," |
CR stay-wins DEC. ." / " dup DEC. ." staying wins," |
||
CR switch-wins DEC. ." / " DEC. ." switching wins." ;</ |
CR switch-wins DEC. ." / " DEC. ." switching wins." ;</syntaxhighlight> |
||
With output: |
With output: |
||
Line 1,848: | Line 1,848: | ||
{{works with|GNU Forth}} |
{{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. |
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. |
||
< |
<syntaxhighlight lang="forth">require random.fs |
||
here seed ! |
here seed ! |
||
Line 1,876: | Line 1,876: | ||
' keep IS applyStrategy run ." Keep door => " .result cr |
' keep IS applyStrategy run ." Keep door => " .result cr |
||
' switch IS applyStrategy run ." Switch door => " .result cr |
' switch IS applyStrategy run ." Switch door => " .result cr |
||
bye</ |
bye</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,886: | Line 1,886: | ||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with|Fortran|90 and later}} |
{{works with|Fortran|90 and later}} |
||
< |
<syntaxhighlight lang="fortran">PROGRAM MONTYHALL |
||
IMPLICIT NONE |
IMPLICIT NONE |
||
Line 1,931: | Line 1,931: | ||
WRITE(*, "(A,F6.2,A)") "Chance of winning by switching is", real(switchcount)/trials*100, "%" |
WRITE(*, "(A,F6.2,A)") "Chance of winning by switching is", real(switchcount)/trials*100, "%" |
||
END PROGRAM MONTYHALL</ |
END PROGRAM MONTYHALL</syntaxhighlight> |
||
Sample Output |
Sample Output |
||
Chance of winning by not switching is 32.82% |
Chance of winning by not switching is 32.82% |
||
Line 1,937: | Line 1,937: | ||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' version 19-01-2019 |
||
' compile with: fbc -s console |
' compile with: fbc -s console |
||
Line 1,971: | Line 1,971: | ||
Print : Print "hit any key to end program" |
Print : Print "hit any key to end program" |
||
Sleep |
Sleep |
||
End</ |
End</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>If you stick to your choice, you have a 33.32 percent chance to win |
<pre>If you stick to your choice, you have a 33.32 percent chance to win |
||
Line 1,985: | Line 1,985: | ||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 2,011: | Line 2,011: | ||
fmt.Printf("Keeper Wins: %d (%3.2f%%)", |
fmt.Printf("Keeper Wins: %d (%3.2f%%)", |
||
keeperWins, (float32(keeperWins) / floatGames * 100)) |
keeperWins, (float32(keeperWins) / floatGames * 100)) |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,019: | Line 2,019: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang="haskell">import System.Random (StdGen, getStdGen, randomR) |
||
trials :: Int |
trials :: Int |
||
Line 2,052: | Line 2,052: | ||
percent n ++ "% of the time." |
percent n ++ "% of the time." |
||
percent n = show $ round $ |
percent n = show $ round $ |
||
100 * (fromIntegral n) / (fromIntegral trials)</ |
100 * (fromIntegral n) / (fromIntegral trials)</syntaxhighlight> |
||
{{libheader|mtl}} |
{{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: |
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: |
||
< |
<syntaxhighlight lang="haskell">import Control.Monad.State |
||
play :: Bool -> State StdGen Door |
play :: Bool -> State StdGen Door |
||
Line 2,077: | Line 2,077: | ||
cars n switch g = (numcars, new_g) |
cars n switch g = (numcars, new_g) |
||
where numcars = length $ filter (== Car) prize_list |
where numcars = length $ filter (== Car) prize_list |
||
(prize_list, new_g) = runState (replicateM n (play switch)) g</ |
(prize_list, new_g) = runState (replicateM n (play switch)) g</syntaxhighlight> |
||
Sample output (for either implementation): |
Sample output (for either implementation): |
||
< |
<syntaxhighlight lang="haskell">The switch strategy succeeds 67% of the time. |
||
The stay strategy succeeds 34% of the time.</ |
The stay strategy succeeds 34% of the time.</syntaxhighlight> |
||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
< |
<syntaxhighlight lang="hicest">REAL :: ndoors=3, doors(ndoors), plays=1E4 |
||
DLG(NameEdit = plays, DNum=1, Button='Go') |
DLG(NameEdit = plays, DNum=1, Button='Go') |
||
Line 2,115: | Line 2,115: | ||
WRITE(ClipBoard, Name) plays, switchWins, stayWins |
WRITE(ClipBoard, Name) plays, switchWins, stayWins |
||
END</ |
END</syntaxhighlight> |
||
< |
<syntaxhighlight lang="hicest">! plays=1E3; switchWins=695; stayWins=305; |
||
! plays=1E4; switchWins=6673; stayWins=3327; |
! plays=1E4; switchWins=6673; stayWins=3327; |
||
! plays=1E5; switchWins=66811; stayWins=33189; |
! plays=1E5; switchWins=66811; stayWins=33189; |
||
! plays=1E6; switchWins=667167; stayWins=332833;</ |
! plays=1E6; switchWins=667167; stayWins=332833;</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
< |
<syntaxhighlight lang="icon">procedure main(arglist) |
||
rounds := integer(arglist[1]) | 10000 |
rounds := integer(arglist[1]) | 10000 |
||
Line 2,140: | Line 2,140: | ||
write("Strategy 2 'Switching' won ", real(strategy2) / rounds ) |
write("Strategy 2 'Switching' won ", real(strategy2) / rounds ) |
||
end</ |
end</syntaxhighlight> |
||
Sample Output:<pre>Monty Hall simulation for 10000 rounds. |
Sample Output:<pre>Monty Hall simulation for 10000 rounds. |
||
Line 2,147: | Line 2,147: | ||
=={{header|Io}}== |
=={{header|Io}}== |
||
< |
<syntaxhighlight lang="io">keepWins := 0 |
||
switchWins := 0 |
switchWins := 0 |
||
doors := 3 |
doors := 3 |
||
Line 2,169: | Line 2,169: | ||
.. "Keeping the same door won #{keepWins} times.\n"\ |
.. "Keeping the same door won #{keepWins} times.\n"\ |
||
.. "Game played #{times} times with #{doors} doors.") interpolate println |
.. "Game played #{times} times with #{doors} doors.") interpolate println |
||
</syntaxhighlight> |
|||
</lang> |
|||
Sample output:<pre>Switching to the other door won 66935 times. |
Sample output:<pre>Switching to the other door won 66935 times. |
||
Keeping the same door won 33065 times. |
Keeping the same door won 33065 times. |
||
Line 2,178: | Line 2,178: | ||
The core of this simulation is picking a random item from a set |
The core of this simulation is picking a random item from a set |
||
< |
<syntaxhighlight lang="j">pick=: {~ ?@#</syntaxhighlight> |
||
And, of course, we will be picking one door from three doors |
And, of course, we will be picking one door from three doors |
||
< |
<syntaxhighlight lang="j">DOORS=:1 2 3</syntaxhighlight> |
||
But note that the simulation code should work just as well with more doors. |
But note that the simulation code should work just as well with more doors. |
||
Line 2,188: | Line 2,188: | ||
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. |
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. |
||
< |
<syntaxhighlight lang="j">scenario=: ((pick@-.,])pick,pick) bind DOORS</syntaxhighlight> |
||
(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.) |
(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: | Line 2,194: | ||
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: |
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: |
||
< |
<syntaxhighlight lang="j">stayWin=: =/@}.</syntaxhighlight> |
||
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. |
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: | Line 2,200: | ||
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: |
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: |
||
< |
<syntaxhighlight lang="j">switchWin=: pick@(DOORS -. }:) = {:</syntaxhighlight> |
||
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. |
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: | Line 2,206: | ||
Finally, we need to run the simulation a thousand times and count how many times each strategy wins: |
Finally, we need to run the simulation a thousand times and count how many times each strategy wins: |
||
< |
<syntaxhighlight lang="j"> +/ (stayWin,switchWin)@scenario"0 i.1000 |
||
320 680</ |
320 680</syntaxhighlight> |
||
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: |
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: |
||
< |
<syntaxhighlight lang="j">simulate=:3 :0 |
||
1 2 3 simulate y |
1 2 3 simulate y |
||
: |
: |
||
Line 2,221: | Line 2,221: | ||
labels=. ];.2 'limit stay switch ' |
labels=. ];.2 'limit stay switch ' |
||
smoutput labels,.":"0 y,+/r |
smoutput labels,.":"0 y,+/r |
||
)</ |
)</syntaxhighlight> |
||
Example use: |
Example use: |
||
< |
<syntaxhighlight lang="j"> simulate 1000 |
||
limit 1000 |
limit 1000 |
||
stay 304 |
stay 304 |
||
switch 696 </ |
switch 696 </syntaxhighlight> |
||
Or, with more doors (and assuming this does not require new rules about how Monty behaves or how the player behaves): |
Or, with more doors (and assuming this does not require new rules about how Monty behaves or how the player behaves): |
||
< |
<syntaxhighlight lang="j"> 1 2 3 4 simulate 1000 |
||
limit 1000 |
limit 1000 |
||
stay 233 |
stay 233 |
||
switch 388 </ |
switch 388 </syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang="java">import java.util.Random; |
||
public class Monty{ |
public class Monty{ |
||
public static void main(String[] args){ |
public static void main(String[] args){ |
||
Line 2,262: | Line 2,262: | ||
System.out.println("Staying wins " + stayWins + " times."); |
System.out.println("Staying wins " + stayWins + " times."); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>Switching wins 21924 times. |
<pre>Switching wins 21924 times. |
||
Line 2,273: | Line 2,273: | ||
This solution can test with n doors, the difference in probability for switching is shown to diminish as the number of doors increases. |
This solution can test with n doors, the difference in probability for switching is shown to diminish as the number of doors increases. |
||
< |
<syntaxhighlight lang="javascript"> |
||
function montyhall(tests, doors) { |
function montyhall(tests, doors) { |
||
'use strict'; |
'use strict'; |
||
Line 2,312: | Line 2,312: | ||
}; |
}; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="javascript"> |
||
montyhall(1000, 3) |
montyhall(1000, 3) |
||
Object {stayWins: "349 34.9%", switchWins: "651 65.1%"} |
Object {stayWins: "349 34.9%", switchWins: "651 65.1%"} |
||
Line 2,322: | Line 2,322: | ||
montyhall(1000, 5) |
montyhall(1000, 5) |
||
Object {stayWins: "202 20.2%", switchWins: "265 26.5%"} |
Object {stayWins: "202 20.2%", switchWins: "265 26.5%"} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Slight modification of the script above for modularity inside of HTML. |
Slight modification of the script above for modularity inside of HTML. |
||
< |
<syntaxhighlight lang="javascript"><html> |
||
<body> |
<body> |
||
Line 2,373: | Line 2,373: | ||
} |
} |
||
</script></ |
</script></syntaxhighlight> |
||
'''Output:''' |
'''Output:''' |
||
< |
<syntaxhighlight lang="javascript">(1000, 3) |
||
First Door Wins: 346 | 34.6% |
First Door Wins: 346 | 34.6% |
||
Switching Door Wins: 654 | 65.4%</ |
Switching Door Wins: 654 | 65.4%</syntaxhighlight> |
||
===Basic Solution=== |
===Basic Solution=== |
||
<!-- http://blog.dreasgrech.com/2011/09/simulating-monty-hall-problem.html --> |
<!-- http://blog.dreasgrech.com/2011/09/simulating-monty-hall-problem.html --> |
||
< |
<syntaxhighlight lang="javascript"> |
||
var totalGames = 10000, |
var totalGames = 10000, |
||
selectDoor = function () { |
selectDoor = function () { |
||
Line 2,427: | Line 2,427: | ||
console.log("Wins when not switching door", play(false)); |
console.log("Wins when not switching door", play(false)); |
||
console.log("Wins when switching door", play(true)); |
console.log("Wins when switching door", play(true)); |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="javascript"> |
||
Playing 10000 games |
Playing 10000 games |
||
Wins when not switching door 3326 |
Wins when not switching door 3326 |
||
Wins when switching door 6630 |
Wins when switching door 6630 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|jq}}== |
=={{header|jq}}== |
||
Line 2,453: | Line 2,453: | ||
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.}} |
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.}} |
||
< |
<syntaxhighlight lang="jq">def rand: |
||
input as $r |
input as $r |
||
| if $r < . then $r else rand end; |
| if $r < . then $r else rand end; |
||
Line 2,470: | Line 2,470: | ||
"Switching wins \(.switchWins) times\n" ; |
"Switching wins \(.switchWins) times\n" ; |
||
1e3, 1e6 | logical_montyHall</ |
1e3, 1e6 | logical_montyHall</syntaxhighlight> |
||
====Simulation==== |
====Simulation==== |
||
{{trans|Kotlin}} |
{{trans|Kotlin}} |
||
< |
<syntaxhighlight lang="jq">def rand: |
||
input as $r |
input as $r |
||
| if $r < . then $r else rand end; |
| if $r < . then $r else rand end; |
||
Line 2,499: | Line 2,499: | ||
"Switching wins \(.switchWins) times\n" ; |
"Switching wins \(.switchWins) times\n" ; |
||
1e3, 1e6 | montyHall</ |
1e3, 1e6 | montyHall</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,517: | Line 2,517: | ||
'''The Literal Simulation Function''' |
'''The Literal Simulation Function''' |
||
< |
<syntaxhighlight lang="julia">using Printf |
||
function play_mh_literal{T<:Integer}(ncur::T=3, ncar::T=1) |
function play_mh_literal{T<:Integer}(ncur::T=3, ncar::T=1) |
||
Line 2,539: | Line 2,539: | ||
return (isstickwin, isswitchwin) |
return (isstickwin, isswitchwin) |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''The Clean Simulation Function''' |
'''The Clean Simulation Function''' |
||
<syntaxhighlight lang="julia"> |
|||
<lang Julia> |
|||
function play_mh_clean{T<:Integer}(ncur::T=3, ncar::T=1) |
function play_mh_clean{T<:Integer}(ncur::T=3, ncar::T=1) |
||
ncar < ncur || throw(DomainError()) |
ncar < ncur || throw(DomainError()) |
||
Line 2,554: | Line 2,554: | ||
return (isstickwin, isswitchwin) |
return (isstickwin, isswitchwin) |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Supporting Functions''' |
'''Supporting Functions''' |
||
<syntaxhighlight lang="julia"> |
|||
<lang Julia> |
|||
function mh_results{T<:Integer}(ncur::T, ncar::T, |
function mh_results{T<:Integer}(ncur::T, ncar::T, |
||
nruns::T, play_mh::Function) |
nruns::T, play_mh::Function) |
||
Line 2,602: | Line 2,602: | ||
return nothing |
return nothing |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Main''' |
'''Main''' |
||
<syntaxhighlight lang="julia"> |
|||
<lang Julia> |
|||
for i in 3:5, j in 1:(i-2) |
for i in 3:5, j in 1:(i-2) |
||
show_simulation(i, j, 10^5) |
show_simulation(i, j, 10^5) |
||
end |
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. |
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,677: | Line 2,677: | ||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
{{trans|Java}} |
{{trans|Java}} |
||
< |
<syntaxhighlight lang="scala">// version 1.1.2 |
||
import java.util.Random |
import java.util.Random |
||
Line 2,704: | Line 2,704: | ||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |
||
montyHall(1_000_000) |
montyHall(1_000_000) |
||
}</ |
}</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
{{out}} |
{{out}} |
||
Line 2,714: | Line 2,714: | ||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
<syntaxhighlight lang="lb"> |
|||
<lang lb> |
|||
'adapted from BASIC solution |
'adapted from BASIC solution |
||
DIM doors(3) '0 is a goat, 1 is a car |
DIM doors(3) '0 is a goat, 1 is a car |
||
Line 2,740: | Line 2,740: | ||
PRINT "Switching wins "; switchWins; " times." |
PRINT "Switching wins "; switchWins; " times." |
||
PRINT "Staying wins "; stayWins; " times." |
PRINT "Staying wins "; stayWins; " times." |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,748: | Line 2,748: | ||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua">function playgame(player) |
||
local car = math.random(3) |
local car = math.random(3) |
||
local pchoice = player.choice() |
local pchoice = player.choice() |
||
Line 2,764: | Line 2,764: | ||
for i = 1, 20000 do playgame(player) end |
for i = 1, 20000 do playgame(player) end |
||
print(player.wins) |
print(player.wins) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Lua/Torch}}== |
=={{header|Lua/Torch}}== |
||
< |
<syntaxhighlight lang="lua">function montyHall(n) |
||
local car = torch.LongTensor(n):random(3) -- door with car |
local car = torch.LongTensor(n):random(3) -- door with car |
||
local choice = torch.LongTensor(n):random(3) -- player's choice |
local choice = torch.LongTensor(n):random(3) -- player's choice |
||
Line 2,793: | Line 2,793: | ||
end |
end |
||
montyStats(1e7)</ |
montyStats(1e7)</syntaxhighlight> |
||
Output for 10 million samples: |
Output for 10 million samples: |
||
Line 2,802: | Line 2,802: | ||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module CheckIt { |
Module CheckIt { |
||
Enum Strat {Stay, Random, Switch} |
Enum Strat {Stay, Random, Switch} |
||
Line 2,847: | Line 2,847: | ||
} |
} |
||
CheckIt |
CheckIt |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,856: | Line 2,856: | ||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica"> montyHall[nGames_] := |
||
Module[{r, winningDoors, firstChoices, nStayWins, nSwitchWins, s}, |
Module[{r, winningDoors, firstChoices, nStayWins, nSwitchWins, s}, |
||
r := RandomInteger[{1, 3}, nGames]; |
r := RandomInteger[{1, 3}, nGames]; |
||
Line 2,865: | Line 2,865: | ||
Grid[{{"Strategy", "Wins", "Win %"}, {"Stay", Row[{nStayWins, "/", nGames}], s=N[100 nStayWins/nGames]}, |
Grid[{{"Strategy", "Wins", "Win %"}, {"Stay", Row[{nStayWins, "/", nGames}], s=N[100 nStayWins/nGames]}, |
||
{"Switch", Row[{nSwitchWins, "/", nGames}], 100 - s}}, Frame -> All]]</ |
{"Switch", Row[{nSwitchWins, "/", nGames}], 100 - s}}, Frame -> All]]</syntaxhighlight> |
||
;Usage: |
;Usage: |
||
<lang |
<syntaxhighlight lang="mathematica">montyHall[100000]</syntaxhighlight> |
||
[[File:MontyHall.jpg]] |
[[File:MontyHall.jpg]] |
||
=={{header|MATLAB}}== |
=={{header|MATLAB}}== |
||
< |
<syntaxhighlight lang="matlab">function montyHall(numDoors,numSimulations) |
||
assert(numDoors > 2); |
assert(numDoors > 2); |
||
Line 2,928: | Line 2,928: | ||
disp(sprintf('Switch win percentage: %f%%\nStay win percentage: %f%%\n', [switchedDoors(1)/sum(switchedDoors),stayed(1)/sum(stayed)] * 100)); |
disp(sprintf('Switch win percentage: %f%%\nStay win percentage: %f%%\n', [switchedDoors(1)/sum(switchedDoors),stayed(1)/sum(stayed)] * 100)); |
||
end</ |
end</syntaxhighlight> |
||
Output: |
Output: |
||
< |
<syntaxhighlight lang="matlab">>> montyHall(3,100000) |
||
Switch win percentage: 66.705972% |
Switch win percentage: 66.705972% |
||
Stay win percentage: 33.420062%</ |
Stay win percentage: 33.420062%</syntaxhighlight> |
||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
< |
<syntaxhighlight lang="maxscript">fn montyHall choice switch = |
||
( |
( |
||
doors = #(false, false, false) |
doors = #(false, false, false) |
||
Line 2,960: | Line 2,960: | ||
iterations = 10000 |
iterations = 10000 |
||
format ("Stay strategy:%\%\n") (iterate iterations false) |
format ("Stay strategy:%\%\n") (iterate iterations false) |
||
format ("Switch strategy:%\%\n") (iterate iterations true)</ |
format ("Switch strategy:%\%\n") (iterate iterations true)</syntaxhighlight> |
||
Output: |
Output: |
||
< |
<syntaxhighlight lang="maxscript">Stay strategy:33.77% |
||
Switch strategy:66.84%</ |
Switch strategy:66.84%</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
Line 2,969: | Line 2,969: | ||
{{trans|REXX}} |
{{trans|REXX}} |
||
{{trans|PL/I}} |
{{trans|PL/I}} |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx ************************************************************ |
||
* 30.08.2013 Walter Pachl translated from Java/REXX/PL/I |
* 30.08.2013 Walter Pachl translated from Java/REXX/PL/I |
||
**********************************************************************/ |
**********************************************************************/ |
||
Line 3,003: | Line 3,003: | ||
method r3 static |
method r3 static |
||
rand=random() |
rand=random() |
||
return rand.nextInt(3) + 1</ |
return rand.nextInt(3) + 1</syntaxhighlight> |
||
Output |
Output |
||
<pre> |
<pre> |
||
Line 3,012: | Line 3,012: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="nim">import random |
||
randomize() |
randomize() |
||
Line 3,049: | Line 3,049: | ||
echo "Stay = ",stay |
echo "Stay = ",stay |
||
echo "Switch = ",switch</ |
echo "Switch = ",switch</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>Stay = 337 |
<pre>Stay = 337 |
||
Line 3,055: | Line 3,055: | ||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml">let trials = 10000 |
||
type door = Car | Goat |
type door = Car | Goat |
||
Line 3,083: | Line 3,083: | ||
strat (100. *. (float n /. float trials)) in |
strat (100. *. (float n /. float trials)) in |
||
msg "switch" switch; |
msg "switch" switch; |
||
msg "stay" stay</ |
msg "stay" stay</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
< |
<syntaxhighlight lang="parigp">test(trials)={ |
||
my(stay=0,change=0); |
my(stay=0,change=0); |
||
for(i=1,trials, |
for(i=1,trials, |
||
Line 3,098: | Line 3,098: | ||
}; |
}; |
||
test(1e4)</ |
test(1e4)</syntaxhighlight> |
||
Output: |
Output: |
||
Line 3,106: | Line 3,106: | ||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
< |
<syntaxhighlight lang="pascal">program MontyHall; |
||
uses |
uses |
||
Line 3,156: | Line 3,156: | ||
end. |
end. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
Line 3,165: | Line 3,165: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">#! /usr/bin/perl |
||
use strict; |
use strict; |
||
my $trials = 10000; |
my $trials = 10000; |
||
Line 3,191: | Line 3,191: | ||
print "Stay win ratio " . (100.0 * $stay/$trials) . "\n"; |
print "Stay win ratio " . (100.0 * $stay/$trials) . "\n"; |
||
print "Switch win ratio " . (100.0 * $switch/$trials) . "\n";</ |
print "Switch win ratio " . (100.0 * $switch/$trials) . "\n";</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
Modified copy of [[Monty_Hall_problem#Euphoria|Euphoria]] |
Modified copy of [[Monty_Hall_problem#Euphoria|Euphoria]] |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<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> |
<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: | Line 3,212: | ||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
<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> |
<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> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,221: | Line 3,221: | ||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php"><?php |
||
function montyhall($iterations){ |
function montyhall($iterations){ |
||
$switch_win = 0; |
$switch_win = 0; |
||
Line 3,247: | Line 3,247: | ||
montyhall(10000); |
montyhall(10000); |
||
?></ |
?></syntaxhighlight> |
||
Output: |
Output: |
||
<pre>Iterations: 10000 - Stayed wins: 3331 (33.31%) - Switched wins: 6669 (66.69%)</pre> |
<pre>Iterations: 10000 - Stayed wins: 3331 (33.31%) - Switched wins: 6669 (66.69%)</pre> |
||
=={{header|Picat}}== |
=={{header|Picat}}== |
||
< |
<syntaxhighlight lang="picat">go => |
||
_ = random2(), % different seed |
_ = random2(), % different seed |
||
member(Rounds,[1000,10_000,100_000,1_000_000,10_000_000]), |
member(Rounds,[1000,10_000,100_000,1_000_000,10_000_000]), |
||
Line 3,280: | Line 3,280: | ||
choice(N) = random(1,N). |
choice(N) = random(1,N). |
||
pick(L) = L[random(1,L.len)].</ |
pick(L) = L[random(1,L.len)].</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,304: | Line 3,304: | ||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(de montyHall (Keep) |
||
(let (Prize (rand 1 3) Choice (rand 1 3)) |
(let (Prize (rand 1 3) Choice (rand 1 3)) |
||
(if Keep # Keeping the first choice? |
(if Keep # Keeping the first choice? |
||
Line 3,322: | Line 3,322: | ||
(do 10000 (and (montyHall NIL) (inc 'Cnt))) |
(do 10000 (and (montyHall NIL) (inc 'Cnt))) |
||
(format Cnt 2) ) |
(format Cnt 2) ) |
||
" %" )</ |
" %" )</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>Strategy KEEP -> 33.01 % |
<pre>Strategy KEEP -> 33.01 % |
||
Line 3,329: | Line 3,329: | ||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
{{trans|Java}} |
{{trans|Java}} |
||
< |
<syntaxhighlight lang="pli">*process source attributes xref; |
||
ziegen: Proc Options(main); |
ziegen: Proc Options(main); |
||
/* REXX *************************************************************** |
/* REXX *************************************************************** |
||
Line 3,366: | Line 3,366: | ||
Return(res); |
Return(res); |
||
End; |
End; |
||
End;</ |
End;</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 3,376: | Line 3,376: | ||
Use ghostscript or print this to a postscript printer |
Use ghostscript or print this to a postscript printer |
||
<syntaxhighlight lang="postscript">%!PS |
|||
<lang PostScript>%!PS |
|||
/Courier % name the desired font |
/Courier % name the desired font |
||
20 selectfont % choose the size in points and establish |
20 selectfont % choose the size in points and establish |
||
Line 3,411: | Line 3,411: | ||
showpage % print all on the page</ |
showpage % print all on the page</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
Line 3,420: | Line 3,420: | ||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
< |
<syntaxhighlight lang="powershell">#Declaring variables |
||
$intIterations = 10000 |
$intIterations = 10000 |
||
$intKept = 0 |
$intKept = 0 |
||
Line 3,473: | Line 3,473: | ||
Write-Host "Keep : $intKept ($($intKept/$intIterations*100)%)" |
Write-Host "Keep : $intKept ($($intKept/$intIterations*100)%)" |
||
Write-Host "Switch: $intSwitched ($($intSwitched/$intIterations*100)%)" |
Write-Host "Switch: $intSwitched ($($intSwitched/$intIterations*100)%)" |
||
Write-Host ""</ |
Write-Host ""</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>Results through 10000 iterations: |
<pre>Results through 10000 iterations: |
||
Line 3,481: | Line 3,481: | ||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
{{works with|GNU Prolog}} |
{{works with|GNU Prolog}} |
||
<syntaxhighlight lang="prolog"> |
|||
<lang Prolog> |
|||
:- initialization(main). |
:- initialization(main). |
||
Line 3,525: | Line 3,525: | ||
win_count(1000, false, 0, StayTotal), |
win_count(1000, false, 0, StayTotal), |
||
format('Staying wins ~d out of 1000.\n', [StayTotal]). |
format('Staying wins ~d out of 1000.\n', [StayTotal]). |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,533: | Line 3,533: | ||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">Structure wins |
||
stay.i |
stay.i |
||
redecide.i |
redecide.i |
||
Line 3,567: | Line 3,567: | ||
PrintN("Wins when redeciding: " + Str(results\redecide) + " (" + StrD(results\redecide / #Tries * 100, 2) + "% chance)") |
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)") |
PrintN("Wins when sticking: " + Str(results\stay) + " (" + StrD(results\stay / #Tries * 100, 2) + "% chance)") |
||
Input()</ |
Input()</syntaxhighlight> |
||
Output:<pre>Trial runs for each option: 1000000 |
Output:<pre>Trial runs for each option: 1000000 |
||
Line 3,574: | Line 3,574: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">''' |
||
I could understand the explanation of the Monty Hall problem |
I could understand the explanation of the Monty Hall problem |
||
but needed some more evidence |
but needed some more evidence |
||
Line 3,618: | Line 3,618: | ||
print sum(monty_hall(randrange(3), switch=True) |
print sum(monty_hall(randrange(3), switch=True) |
||
for x in range(iterations)), |
for x in range(iterations)), |
||
print "out of", iterations, "times.\n"</ |
print "out of", iterations, "times.\n"</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
<pre>Monty Hall problem simulation: |
<pre>Monty Hall problem simulation: |
||
Line 3,630: | Line 3,630: | ||
===Python 3 version: === |
===Python 3 version: === |
||
Another (simpler in my opinion), way to do this is below, also in python 3: |
Another (simpler in my opinion), way to do this is below, also in python 3: |
||
< |
<syntaxhighlight lang="python">import random |
||
#1 represents a car |
#1 represents a car |
||
#0 represent a goat |
#0 represent a goat |
||
Line 3,662: | Line 3,662: | ||
print("Stay =",stay) |
print("Stay =",stay) |
||
print("Switch = ",switch) |
print("Switch = ",switch) |
||
#Done by Sam Witton 09/04/2014</ |
#Done by Sam Witton 09/04/2014</syntaxhighlight> |
||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
< |
<syntaxhighlight lang="quackery"> [ $ "bigrat.qky" loadfile ] now! |
||
[ 0 ( number of cars when not changing choice ) |
[ 0 ( number of cars when not changing choice ) |
||
Line 3,683: | Line 3,683: | ||
say "Approximate ratio of car wins with strategy A over strategy B: " |
say "Approximate ratio of car wins with strategy A over strategy B: " |
||
swap 100 round |
swap 100 round |
||
vulgar$ echo$ cr ] is trials ( n --> )</ |
vulgar$ echo$ cr ] is trials ( n --> )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,708: | Line 3,708: | ||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang="rsplus">set.seed(19771025) # set the seed to set the same results as this code |
||
N <- 10000 # trials |
N <- 10000 # trials |
||
true_answers <- sample(1:3, N, replace=TRUE) |
true_answers <- sample(1:3, N, replace=TRUE) |
||
Line 3,765: | Line 3,765: | ||
change <- runif(N) >= .5 |
change <- runif(N) >= .5 |
||
random_switch[change] <- other_door[change] |
random_switch[change] <- other_door[change] |
||
summary(random_switch == true_answers)</ |
summary(random_switch == true_answers)</syntaxhighlight> |
||
Line 3,831: | Line 3,831: | ||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
<syntaxhighlight lang="racket"> |
|||
<lang Racket> |
|||
#lang racket |
#lang racket |
||
Line 3,868: | Line 3,868: | ||
(for-each test-strategy (list keep-choice change-choice)) |
(for-each test-strategy (list keep-choice change-choice)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Sample Output: |
Sample Output: |
||
Line 3,881: | Line 3,881: | ||
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]]. |
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]]. |
||
<lang |
<syntaxhighlight lang="raku" line>enum Prize <Car Goat>; |
||
enum Strategy <Stay Switch>; |
enum Strategy <Stay Switch>; |
||
Line 3,919: | Line 3,919: | ||
'% of the time.' |
'% of the time.' |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>With 3 doors: |
<pre>With 3 doors: |
||
Line 3,931: | Line 3,931: | ||
===version 1=== |
===version 1=== |
||
{{trans|Java}} |
{{trans|Java}} |
||
< |
<syntaxhighlight lang="rexx">/* REXX *************************************************************** |
||
* 30.08.2013 Walter Pachl derived from Java |
* 30.08.2013 Walter Pachl derived from Java |
||
**********************************************************************/ |
**********************************************************************/ |
||
Line 3,961: | Line 3,961: | ||
Say 'NetRexx:' time('E') 'seconds' |
Say 'NetRexx:' time('E') 'seconds' |
||
Exit |
Exit |
||
r3: Return random(2)+1</ |
r3: Return random(2)+1</syntaxhighlight> |
||
Output for 1000000 samples: |
Output for 1000000 samples: |
||
<pre> |
<pre> |
||
Line 3,985: | Line 3,985: | ||
===version 2=== |
===version 2=== |
||
< |
<syntaxhighlight 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.*/ |
parse arg # seed . /*obtain the optional args from the CL.*/ |
||
if #=='' | #=="," then #= 1000000 /*Not specified? Then 1 million trials*/ |
if #=='' | #=="," then #= 1000000 /*Not specified? Then 1 million trials*/ |
||
Line 3,998: | Line 3,998: | ||
say 'switching wins ' format(wins.0 / # * 100, , 1)"% of the time." |
say 'switching wins ' format(wins.0 / # * 100, , 1)"% of the time." |
||
say ' staying wins ' format(wins.1 / # * 100, , 1)"% of the time." ; say |
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. */</ |
say 'performed ' # " times with 3 doors." /*stick a fork in it, we're all done. */</syntaxhighlight> |
||
{{out|output|text= when using the default inputs:}} |
{{out|output|text= when using the default inputs:}} |
||
<pre> |
<pre> |
||
Line 4,008: | Line 4,008: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
total = 10000 |
total = 10000 |
||
swapper = 0 |
swapper = 0 |
||
Line 4,031: | Line 4,031: | ||
see "the 'sticker' won " + sticker + " times (" + floor(sticker/total*100) + "%)" + nl |
see "the 'sticker' won " + sticker + " times (" + floor(sticker/total*100) + "%)" + nl |
||
see "the 'swapper' won " + swapper + " times (" + floor(swapper/total*100) + "%)" + nl |
see "the 'swapper' won " + swapper + " times (" + floor(swapper/total*100) + "%)" + nl |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 4,041: | Line 4,041: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">n = 10_000 #number of times to play |
||
stay = switch = 0 #sum of each strategy's wins |
stay = switch = 0 #sum of each strategy's wins |
||
Line 4,067: | Line 4,067: | ||
puts "Staying wins %.2f%% of the time." % (100.0 * stay / n) |
puts "Staying wins %.2f%% of the time." % (100.0 * stay / n) |
||
puts "Switching wins %.2f%% of the time." % (100.0 * switch / n)</ |
puts "Switching wins %.2f%% of the time." % (100.0 * switch / n)</syntaxhighlight> |
||
Sample Output: |
Sample Output: |
||
<pre>Staying wins 33.84% of the time. |
<pre>Staying wins 33.84% of the time. |
||
Line 4,073: | Line 4,073: | ||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<syntaxhighlight lang="runbasic">' adapted from BASIC solution |
||
input "Number of tries;";tries ' gimme the number of iterations |
input "Number of tries;";tries ' gimme the number of iterations |
||
Line 4,094: | Line 4,094: | ||
PRINT " Result for ";tries;" games." |
PRINT " Result for ";tries;" games." |
||
PRINT "Switching wins ";switchWins; " times." |
PRINT "Switching wins ";switchWins; " times." |
||
PRINT " Staying wins ";stayWins; " times."</ |
PRINT " Staying wins ";stayWins; " times."</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
{{libheader|rand}} |
{{libheader|rand}} |
||
< |
<syntaxhighlight lang="rust">extern crate rand; |
||
use rand::Rng; |
use rand::Rng; |
||
use rand::seq::SliceRandom; |
use rand::seq::SliceRandom; |
||
Line 4,124: | Line 4,124: | ||
percent = switch_wins as f64 / GAMES as f64 * 100.0 |
percent = switch_wins as f64 / GAMES as f64 * 100.0 |
||
); |
); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">import scala.util.Random |
||
object MontyHallSimulation { |
object MontyHallSimulation { |
||
Line 4,159: | Line 4,159: | ||
switchStrategyWins, percent(switchStrategyWins))) |
switchStrategyWins, percent(switchStrategyWins))) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Sample: |
Sample: |
||
Line 4,170: | Line 4,170: | ||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme">(define (random-from-list list) (list-ref list (random (length list)))) |
||
(define (random-permutation list) |
(define (random-permutation list) |
||
(if (null? list) |
(if (null? list) |
||
Line 4,239: | Line 4,239: | ||
;; > (compare-strategies 1000000) |
;; > (compare-strategies 1000000) |
||
;; (stay-strategy won with probability 33.3638 % |
;; (stay-strategy won with probability 33.3638 % |
||
;; and switch-strategy won with probability 66.716 %)</ |
;; and switch-strategy won with probability 66.716 %)</syntaxhighlight> |
||
=={{header|Scilab}}== |
=={{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.}} |
{{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.}} |
||
<lang>// How it works: |
<syntaxhighlight lang="text">// How it works: |
||
// MontyHall() is a function with argument switch: |
// MontyHall() is a function with argument switch: |
||
// it will be called 100000 times with switch=%T, |
// it will be called 100000 times with switch=%T, |
||
Line 4,281: | Line 4,281: | ||
end |
end |
||
disp("Switching, one wins"+ascii(10)+string(wins_switch)+" games out of "+string(games)) |
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))</ |
disp("Staying, one wins"+ascii(10)+string(wins_stay)+" games out of "+string(games))</syntaxhighlight> |
||
Output: |
Output: |
||
Line 4,294: | Line 4,294: | ||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
const proc: main is func |
const proc: main is func |
||
Line 4,316: | Line 4,316: | ||
writeln("Switching wins " <& switchWins <& " times"); |
writeln("Switching wins " <& switchWins <& " times"); |
||
writeln("Staying wins " <& stayWins <& " times"); |
writeln("Staying wins " <& stayWins <& " times"); |
||
end func;</ |
end func;</syntaxhighlight> |
||
Output: |
Output: |
||
Line 4,325: | Line 4,325: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">var n = 1000 # number of times to play |
||
var switchWins = (var stayWins = 0) # sum of each strategy's wins |
var switchWins = (var stayWins = 0) # sum of each strategy's wins |
||
Line 4,345: | Line 4,345: | ||
say ("Staying wins %.2f%% of the time." % (100.0 * stayWins / n)) |
say ("Staying wins %.2f%% of the time." % (100.0 * stayWins / n)) |
||
say ("Switching wins %.2f%% of the time." % (100.0 * switchWins / n))</ |
say ("Switching wins %.2f%% of the time." % (100.0 * switchWins / n))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,354: | Line 4,354: | ||
=={{header|SPAD}}== |
=={{header|SPAD}}== |
||
{{works with|FriCAS, OpenAxiom, Axiom}} |
{{works with|FriCAS, OpenAxiom, Axiom}} |
||
<syntaxhighlight lang="spad"> |
|||
<lang SPAD> |
|||
montyHall(n) == |
montyHall(n) == |
||
wd:=[1+random(3) for j in 1..n] |
wd:=[1+random(3) for j in 1..n] |
||
Line 4,361: | Line 4,361: | ||
p:=(st/n)::DoubleFloat |
p:=(st/n)::DoubleFloat |
||
FORMAT(nil,"stay: ~A, switch: ~A",p,1-p)$Lisp |
FORMAT(nil,"stay: ~A, switch: ~A",p,1-p)$Lisp |
||
</syntaxhighlight> |
|||
</lang> |
|||
Domain:[http://fricas.github.io/api/Integer.html?highlight=random Integer] |
Domain:[http://fricas.github.io/api/Integer.html?highlight=random Integer] |
||
Line 4,384: | Line 4,384: | ||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
< |
<syntaxhighlight lang="stata">clear |
||
set obs 1000000 |
set obs 1000000 |
||
gen car=runiformint(1,3) |
gen car=runiformint(1,3) |
||
Line 4,393: | Line 4,393: | ||
gen choice2=6-shown-choice1 |
gen choice2=6-shown-choice1 |
||
gen succ2=car==choice2 |
gen succ2=car==choice2 |
||
tabstat succ1 succ2, s(mean)</ |
tabstat succ1 succ2, s(mean)</syntaxhighlight> |
||
'''Output''' |
'''Output''' |
||
Line 4,404: | Line 4,404: | ||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">import Foundation |
||
func montyHall(doors: Int = 3, guess: Int, switch: Bool) -> Bool { |
func montyHall(doors: Int = 3, guess: Int, switch: Bool) -> Bool { |
||
Line 4,426: | Line 4,426: | ||
print("Switching would've won \((Double(switchWins) / Double(switchResults.count)) * 100)% of games") |
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")</ |
print("Not switching would've won \(((Double(switchResults.count - switchWins)) / Double(switchResults.count)) * 100)% of games")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,434: | Line 4,434: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
A simple way of dealing with this one, based on knowledge of the underlying probabilistic system, is to use code like this: |
A simple way of dealing with this one, based on knowledge of the underlying probabilistic system, is to use code like this: |
||
< |
<syntaxhighlight lang="tcl">set stay 0; set change 0; set total 10000 |
||
for {set i 0} {$i<$total} {incr i} { |
for {set i 0} {$i<$total} {incr i} { |
||
if {int(rand()*3) == int(rand()*3)} { |
if {int(rand()*3) == int(rand()*3)} { |
||
Line 4,443: | Line 4,443: | ||
} |
} |
||
puts "Estimate: $stay/$total wins for staying strategy" |
puts "Estimate: $stay/$total wins for staying strategy" |
||
puts "Estimate: $change/$total wins for changing strategy"</ |
puts "Estimate: $change/$total wins for changing strategy"</syntaxhighlight> |
||
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.) |
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. |
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. |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.5 |
||
# Utility: pick a random item from a list |
# Utility: pick a random item from a list |
||
Line 4,512: | Line 4,512: | ||
puts "Estimate: $stay/$total wins for 'staying' strategy" |
puts "Estimate: $stay/$total wins for 'staying' strategy" |
||
puts "Estimate: $change/$total wins for 'changing' strategy" |
puts "Estimate: $change/$total wins for 'changing' strategy" |
||
puts "Estimate: $anew/$total wins for 'picking anew' strategy"</ |
puts "Estimate: $anew/$total wins for 'picking anew' strategy"</syntaxhighlight> |
||
This might then produce output like |
This might then produce output like |
||
Estimate: 3340/10000 wins for 'staying' strategy |
Estimate: 3340/10000 wins for 'staying' strategy |
||
Line 4,521: | Line 4,521: | ||
=={{header|Transact SQL}}== |
=={{header|Transact SQL}}== |
||
T-SQL for general case: |
T-SQL for general case: |
||
<syntaxhighlight lang="transact sql"> |
|||
<lang Transact SQL> |
|||
---- BEGIN ------------ |
---- BEGIN ------------ |
||
create table MONTY_HALL( |
create table MONTY_HALL( |
||
Line 4,563: | Line 4,563: | ||
from MONTY_HALL |
from MONTY_HALL |
||
---- END ------------ |
---- END ------------ |
||
</syntaxhighlight> |
|||
</lang> |
|||
<pre> |
<pre> |
||
% OF WINS FOR KEEP % OF WINS FOR CHANGE % OF WINS FOR RANDOM |
% OF WINS FOR KEEP % OF WINS FOR CHANGE % OF WINS FOR RANDOM |
||
Line 4,572: | Line 4,572: | ||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
{{works with|bash|2.x| and most bash-compatible unix shells}} |
{{works with|bash|2.x| and most bash-compatible unix shells}} |
||
< |
<syntaxhighlight lang="bash">#!/bin/bash |
||
# Simulates the "monty hall" probability paradox and shows results. |
# Simulates the "monty hall" probability paradox and shows results. |
||
# http://en.wikipedia.org/wiki/Monty_Hall_problem |
# http://en.wikipedia.org/wiki/Monty_Hall_problem |
||
Line 4,643: | Line 4,643: | ||
echo "Wins (switch to remaining door): $num_win" |
echo "Wins (switch to remaining door): $num_win" |
||
echo "Losses (first guess was correct): $num_lose" |
echo "Losses (first guess was correct): $num_lose" |
||
exit 0</ |
exit 0</syntaxhighlight> |
||
Output of a few runs: |
Output of a few runs: |
||
<pre> |
<pre> |
||
Line 4,697: | Line 4,697: | ||
for the switching strategy. |
for the switching strategy. |
||
< |
<syntaxhighlight lang="ursala">#import std |
||
#import nat |
#import nat |
||
#import flo |
#import flo |
||
Line 4,713: | Line 4,713: | ||
#show+ |
#show+ |
||
main = ~&plrTS/<'stay: ','switch: '> format* <staying_wins,switching_wins></ |
main = ~&plrTS/<'stay: ','switch: '> format* <staying_wins,switching_wins></syntaxhighlight> |
||
Output will vary slightly for each run due to randomness. |
Output will vary slightly for each run due to randomness. |
||
<pre> |
<pre> |
||
Line 4,724: | Line 4,724: | ||
Vedit macro language does not have random number generator, so one is implemented in subroutine RANDOM (the algorithm was taken from ANSI C library). |
Vedit macro language does not have random number generator, so one is implemented in subroutine RANDOM (the algorithm was taken from ANSI C library). |
||
< |
<syntaxhighlight lang="vedit">#90 = Time_Tick // seed for random number generator |
||
#91 = 3 // random numbers in range 0 to 2 |
#91 = 3 // random numbers in range 0 to 2 |
||
#1 = 0 // wins for "always stay" strategy |
#1 = 0 // wins for "always stay" strategy |
||
Line 4,757: | Line 4,757: | ||
#93 = 0x7fffffff % 48271 |
#93 = 0x7fffffff % 48271 |
||
#90 = (48271 * (#90 % #92) - #93 * (#90 / #92)) & 0x7fffffff |
#90 = (48271 * (#90 % #92) - #93 * (#90 / #92)) & 0x7fffffff |
||
return ((#90 & 0xffff) * #91 / 0x10000)</ |
return ((#90 & 0xffff) * #91 / 0x10000)</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
Line 4,767: | Line 4,767: | ||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
{{trans|Kotlin}} |
{{trans|Kotlin}} |
||
< |
<syntaxhighlight lang="ecmascript">import "random" for Random |
||
var montyHall = Fn.new { |games| |
var montyHall = Fn.new { |games| |
||
Line 4,790: | Line 4,790: | ||
} |
} |
||
montyHall.call(1e6)</ |
montyHall.call(1e6)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,801: | Line 4,801: | ||
=={{header|X++}}== |
=={{header|X++}}== |
||
< |
<syntaxhighlight lang="x++">//Evidence of the Monty Hall solution in Dynamics AX (by Wessel du Plooy - HiGH Software). |
||
int changeWins = 0; |
int changeWins = 0; |
||
Line 4,834: | Line 4,834: | ||
print strFmt("Staying wins %1 times.", noChangeWins); |
print strFmt("Staying wins %1 times.", noChangeWins); |
||
pause; |
pause; |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
Line 4,841: | Line 4,841: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">def Games = 10000; \number of games simulated |
||
int Game, Wins; |
int Game, Wins; |
||
include c:\cxpl\codes; |
include c:\cxpl\codes; |
||
Line 4,871: | Line 4,871: | ||
RlOut(0, float(Wins)/float(Games)*100.0); |
RlOut(0, float(Wins)/float(Games)*100.0); |
||
Text(0, "% of games.^M^J"); |
Text(0, "% of games.^M^J"); |
||
]</ |
]</syntaxhighlight> |
||
Example output: |
Example output: |
||
Line 4,881: | Line 4,881: | ||
=={{header|Yabasic}}== |
=={{header|Yabasic}}== |
||
< |
<syntaxhighlight lang="yabasic"> |
||
numTiradas = 1000000 |
numTiradas = 1000000 |
||
Line 4,903: | Line 4,903: | ||
print "Si cambia, tiene un ", cambia / numTiradas * 100, "% de probabilidades de ganar." |
print "Si cambia, tiene un ", cambia / numTiradas * 100, "% de probabilidades de ganar." |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
{{trans|Go}} |
{{trans|Go}} |
||
< |
<syntaxhighlight lang="zkl">const games=0d100_000; |
||
reg switcherWins=0, keeperWins=0, shown=0; |
reg switcherWins=0, keeperWins=0, shown=0; |
||
Line 4,924: | Line 4,924: | ||
switcherWins, switcherWins.toFloat() / games * 100).println(); |
switcherWins, switcherWins.toFloat() / games * 100).println(); |
||
"Keeper Wins: %,d (%3.2f%%)".fmt( |
"Keeper Wins: %,d (%3.2f%%)".fmt( |
||
keeperWins, keeperWins.toFloat() / games * 100).println();</ |
keeperWins, keeperWins.toFloat() / games * 100).println();</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |