Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,6 @@
---
category:
- Games
- Probability and statistics
from: http://rosettacode.org/wiki/Monty_Hall_problem
note: Discrete math

View file

@ -0,0 +1,40 @@
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
;Rules of the game:
After you have chosen a door, the door remains closed for the time being.
The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
;The question:
Is it to your advantage to change your choice?
;Note:
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
;Task:
Run random simulations of the [[wp:Monty_Hall_problem|Monty Hall]] game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy <u>and show the results</u> in such a way as to make it easy to compare the effects of each strategy.
;References:
:* Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 [https://doi.org/10.1037/0096-3445.132.1.3 DOI: 10.1037/0096-3445.132.1.3]
:* A YouTube video: &nbsp; [https://www.youtube.com/watch?v=4Lb-6rxZxx0 Monty Hall Problem - Numberphile].
<br><br>

View file

@ -0,0 +1,25 @@
V stay = 0
V sw = 0
L 1000
V lst = [1, 0, 0]
random:shuffle(&lst)
V ran = random:(3)
V user = lst[ran]
lst.pop(ran)
V huh = 0
L(i) lst
I i == 0
lst.pop(huh)
L.break
huh++
I user == 1
stay++
I lst[0] == 1
sw++
print(Stay = stay)
print(Switch = sw)

View file

@ -0,0 +1,79 @@
time: equ 2Ch ; MS-DOS syscall to get current time
puts: equ 9 ; MS-DOS syscall to print a string
cpu 8086
bits 16
org 100h
section .text
;;; Initialize the RNG with the current time
mov ah,time
int 21h
mov di,cx ; RNG state is kept in DI and BP
mov bp,dx
mov dx,sw ; While switching doors,
mov bl,1
call simrsl ; run simulations,
mov dx,nsw ; While not switching doors,
xor bl,bl ; run simulations.
;;; Print string in DX, run 65536 simulations (according to BL),
;;; then print the amount of cars won.
simrsl: mov ah,puts ; Print the string
int 21h
xor cx,cx ; Run 65536 simulations
call simul
mov ax,si ; Print amount of cars
mov bx,number ; String pointer
mov cx,10 ; Divisor
.dgt: xor dx,dx ; Divide AX by ten
div cx
add dl,'0' ; Add ASCII '0' to the remainder
dec bx ; Move string pointer backwards
mov [bx],dl ; Store digit in string
test ax,ax ; If quotient not zero,
jnz .dgt ; calculate next digit.
mov dx,bx ; Print string starting at first digit
mov ah,puts
int 21h
ret
;;; Run CX simulations.
;;; If BL = 0, don't switch doors, otherwise, always switch
simul: xor si,si ; SI is the amount of cars won
.loop: call door ; Behind which door is the car?
xchg dl,al ; DL = car door
call door ; Which door does the contestant choose?
xchg ah,al ; AH = contestant door
.monty: call door ; Which door does Monty open?
cmp al,dl ; It can't be the door with the car,
je .monty
cmp al,ah ; or the door the contestant picked.
je .monty
test bl,bl ; Will the contestant switch doors?
jz .nosw
xor ah,al ; If so, he switches
.nosw: cmp ah,dl ; Did he get the car?
jne .next
inc si ; If so, add a car
.next: loop .loop
ret
;;; Generate a pseudorandom byte in AL using "X ABC" method
;;; Use it to select a door (1,2,3).
door: xchg bx,bp ; Load RNG state into byte-addressable
xchg cx,di ; registers.
.loop: inc bl ; X++
xor bh,ch ; A ^= C
xor bh,bl ; A ^= X
add cl,bh ; B += A
mov al,cl ; C' = B
shr al,1 ; C' >>= 1
add al,ch ; C' += C
xor al,bh ; C' ^= A
mov ch,al ; C = C'
and al,3 ; ...but we only want the last two bits,
jz .loop ; and if it was 0, get a new random number.
xchg bx,bp ; Restore the registers
xchg cx,di
ret
section .data
sw: db 'When switching doors: $'
nsw: db 'When not switching doors: $'
db '*****'
number: db 13,10,'$'

View file

@ -0,0 +1,54 @@
INT trials=100 000;
PROC brand = (INT n)INT: 1 + ENTIER (n * random);
PROC percent = (REAL x)STRING: fixed(100.0*x/trials,0,2)+"%";
main:
(
INT prize, choice, show, not shown, new choice;
INT stay winning:=0, change winning:=0, random winning:=0;
INT doors = 3;
[doors-1]INT other door;
TO trials DO
# put the prize somewhere #
prize := brand(doors);
# let the user choose a door #
choice := brand(doors);
# let us take a list of unchoosen doors #
INT k := LWB other door;
FOR j TO doors DO
IF j/=choice THEN other door[k] := j; k+:=1 FI
OD;
# Monty opens one... #
IF choice = prize THEN
# staying the user will win... Monty opens a random port#
show := other door[ brand(doors - 1) ];
not shown := other door[ (show+1) MOD (doors - 1 ) + 1]
ELSE # no random, Monty can open just one door... #
IF other door[1] = prize THEN
show := other door[2];
not shown := other door[1]
ELSE
show := other door[1];
not shown := other door[2]
FI
FI;
# the user randomly choose one of the two closed doors
(one is his/her previous choice, the second is the
one not shown ) #
other door[1] := choice;
other door[2] := not shown;
new choice := other door[ brand(doors - 1) ];
# now let us count if it takes it or not #
IF choice = prize THEN stay winning+:=1 FI;
IF not shown = prize THEN change winning+:=1 FI;
IF new choice = prize THEN random winning+:=1 FI
OD;
print(("Staying: ", percent(stay winning), new line ));
print(("Changing: ", percent(change winning), new line ));
print(("New random choice: ", percent(random winning), new line ))
)

View file

@ -0,0 +1,15 @@
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
[3]
[4] (⎕IO ⎕ML)0 1
[5] prices0 0 1 ⍝ 0=Goat, 1=Car
[6]
[7] ix,/{3?3}¨runs ⍝ random indexes of doors (placement of car)
[8] doors(runs 3)prices[ix] ⍝ matrix of doors
[9] stay+doors[;?3] ⍝ chose randomly one door - is it a car?
[10] swapruns-stay ⍝ If not, then the other one is!
[11]
[12] 'Swap: ',(2100×(swap÷runs)),'% it''s a car'
[13] 'Stay: ',(2100×(stay÷runs)),'% it''s a car'

View file

@ -0,0 +1,57 @@
#!/bin/gawk -f
# Monty Hall problem
BEGIN {
srand()
doors = 3
iterations = 10000
# Behind a door:
EMPTY = "empty"; PRIZE = "prize"
# Algorithm used
KEEP = "keep"; SWITCH="switch"; RAND="random";
#
}
function monty_hall( choice, algorithm ) {
# Set up doors
for ( i=0; i<doors; i++ ) {
door[i] = EMPTY
}
# One door with prize
door[int(rand()*doors)] = PRIZE
chosen = door[choice]
del door[choice]
#if you didn't choose the prize first time around then
# that will be the alternative
alternative = (chosen == PRIZE) ? EMPTY : PRIZE
if( algorithm == KEEP) {
return chosen
}
if( algorithm == SWITCH) {
return alternative
}
return rand() <0.5 ? chosen : alternative
}
function simulate(algo){
prizecount = 0
for(j=0; j< iterations; j++){
if( monty_hall( int(rand()*doors), algo) == PRIZE) {
prizecount ++
}
}
printf " Algorithm %7s: prize count = %i, = %6.2f%%\n", \
algo, prizecount,prizecount*100/iterations
}
BEGIN {
print "\nMonty Hall problem simulation:"
print doors, "doors,", iterations, "iterations.\n"
simulate(KEEP)
simulate(SWITCH)
simulate(RAND)
}

View file

@ -0,0 +1,9 @@
bash$ ./monty_hall.awk
Monty Hall problem simulation:
3 doors, 10000 iterations.
Algorithm keep: prize count = 3411, = 34.11%
Algorithm switch: prize count = 6655, = 66.55%
Algorithm random: prize count = 4991, = 49.91%
bash$

View file

@ -0,0 +1,32 @@
package {
import flash.display.Sprite;
public class MontyHall extends Sprite
{
public function MontyHall()
{
var iterations:int = 30000;
var switchWins:int = 0;
var stayWins:int = 0;
for (var i:int = 0; i < iterations; i++)
{
var doors:Array = [0, 0, 0];
doors[Math.floor(Math.random() * 3)] = 1;
var choice:int = Math.floor(Math.random() * 3);
var shown:int;
do
{
shown = Math.floor(Math.random() * 3);
} while (doors[shown] == 1 || shown == choice);
stayWins += doors[choice];
switchWins += doors[3 - choice - shown];
}
trace("Switching wins " + switchWins + " times. (" + (switchWins / iterations) * 100 + "%)");
trace("Staying wins " + stayWins + " times. (" + (stayWins / iterations) * 100 + "%)");
}
}
}

View file

@ -0,0 +1,76 @@
-- Monty Hall Game
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
with ada.Numerics.Discrete_Random;
procedure Monty_Stats is
Num_Iterations : Positive := 100000;
type Action_Type is (Stay, Switch);
type Prize_Type is (Goat, Pig, Car);
type Door_Index is range 1..3;
package Random_Prize is new Ada.Numerics.Discrete_Random(Door_Index);
use Random_Prize;
Seed : Generator;
Doors : array(Door_Index) of Prize_Type;
procedure Set_Prizes is
Prize_Index : Door_Index;
Booby_Prize : Prize_Type := Goat;
begin
Reset(Seed);
Prize_Index := Random(Seed);
Doors(Prize_Index) := Car;
for I in Doors'range loop
if I /= Prize_Index then
Doors(I) := Booby_Prize;
Booby_Prize := Prize_Type'Succ(Booby_Prize);
end if;
end loop;
end Set_Prizes;
function Play(Action : Action_Type) return Prize_Type is
Chosen : Door_Index := Random(Seed);
Monty : Door_Index;
begin
Set_Prizes;
for I in Doors'range loop
if I /= Chosen and Doors(I) /= Car then
Monty := I;
end if;
end loop;
if Action = Switch then
for I in Doors'range loop
if I /= Monty and I /= Chosen then
Chosen := I;
exit;
end if;
end loop;
end if;
return Doors(Chosen);
end Play;
Winners : Natural;
Pct : Float;
begin
Winners := 0;
for I in 1..Num_Iterations loop
if Play(Stay) = Car then
Winners := Winners + 1;
end if;
end loop;
Put("Stay : count" & Natural'Image(Winners) & " = ");
Pct := Float(Winners * 100) / Float(Num_Iterations);
Put(Item => Pct, Aft => 2, Exp => 0);
Put_Line("%");
Winners := 0;
for I in 1..Num_Iterations loop
if Play(Switch) = Car then
Winners := Winners + 1;
end if;
end loop;
Put("Switch : count" & Natural'Image(Winners) & " = ");
Pct := Float(Winners * 100) / Float(Num_Iterations);
Put(Item => Pct, Aft => 2, Exp => 0);
Put_Line("%");
end Monty_Stats;

View file

@ -0,0 +1,24 @@
stay: 0
swit: 0
loop 1..1000 'i [
lst: shuffle new [1 0 0]
rand: random 0 2
user: lst\[rand]
remove 'lst rand
huh: 0
loop lst 'i [
if zero? i [
remove 'lst huh
break
]
huh: huh + 1
]
if user=1 -> stay: stay+1
if and? [0 < size lst] [1 = first lst] -> swit: swit+1
]
print ["Stay:" stay]
print ["Switch:" swit]

View file

@ -0,0 +1,34 @@
#SingleInstance, Force
Iterations = 1000
Loop, %Iterations%
{
If Monty_Hall(1)
Correct_Change++
Else
Incorrect_Change++
If Monty_Hall(2)
Correct_Random++
Else
Incorrect_Random++
If Monty_Hall(3)
Correct_Stay++
Else
Incorrect_Stay++
}
Percent_Change := round(Correct_Change / Iterations * 100)
Percent_Stay := round(Correct_Stay / Iterations * 100)
Percent_Random := round(Correct_Random / Iterations * 100)
MsgBox,, Monty Hall Problem, These are the results:`r`n`r`nWhen I changed my guess, I got %Correct_Change% of %Iterations% (that's %Incorrect_Change% incorrect). That's %Percent_Change%`% correct.`r`n`r`nWhen I randomly changed my guess, I got %Correct_Random% of %Iterations% (that's %Incorrect_Random% incorrect). That's %Percent_Random%`% correct.`r`n`r`nWhen I stayed with my first guess, I got %Correct_Stay% of %Iterations% (that's %Incorrect_Stay% incorrect). That's %Percent_Stay%`% correct.
ExitApp
Monty_Hall(Mode) ;Mode is 1 for change, 2 for random, or 3 for stay
{
Random, guess, 1, 3
Random, actual, 1, 3
Random, rand, 1, 2
show := guess = actual ? guess = 3 ? guess - rand : guess = 1 ? guess+rand : guess + 2*rand - 3 : 6 - guess - actual
Mode := Mode = 2 ? 2*rand - 1: Mode
Return, Mode = 1 ? 6 - guess - show = actual : guess = actual
}

View file

@ -0,0 +1,19 @@
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."

View file

@ -0,0 +1,23 @@
numTiradas = 1000000
permanece = 0
cambia = 0
for i = 1 to numTiradas
pta_coche = int(rand * 3) + 1
pta_elegida = int(rand * 3) + 1
if pta_coche <> pta_elegida then
pta_montys = 6 - pta_coche - pta_elegida
else
do
pta_montys = int(Rand * 3) + 1
until pta_montys <> pta_coche
end if
# manteenr elección
if pta_coche = pta_elegida then permanece += 1
# cambiar elección
if pta_coche = 6 - pta_montys - pta_elegida then cambia +=1
next i
print "Si mantiene su elección, tiene un "; permanece / numTiradas * 100 ;"% de probabilidades de ganar."
print "Si cambia, tiene un "; cambia / numTiradas * 100; "% de probabilidades de ganar."
end

View file

@ -0,0 +1,21 @@
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);"%)"

View file

@ -0,0 +1,57 @@
#include <iostream>
#include <cstdlib>
#include <ctime>
int randint(int n)
{
return (1.0*n*std::rand())/(1.0+RAND_MAX);
}
int other(int doorA, int doorB)
{
int doorC;
if (doorA == doorB)
{
doorC = randint(2);
if (doorC >= doorA)
++doorC;
}
else
{
for (doorC = 0; doorC == doorA || doorC == doorB; ++doorC)
{
// empty
}
}
return doorC;
}
int check(int games, bool change)
{
int win_count = 0;
for (int game = 0; game < games; ++game)
{
int const winning_door = randint(3);
int const original_choice = randint(3);
int open_door = other(original_choice, winning_door);
int const selected_door = change?
other(open_door, original_choice)
: original_choice;
if (selected_door == winning_door)
++win_count;
}
return win_count;
}
int main()
{
std::srand(std::time(0));
int games = 10000;
int wins_stay = check(games, false);
int wins_change = check(games, true);
std::cout << "staying: " << 100.0*wins_stay/games << "%, changing: " << 100.0*wins_change/games << "%\n";
}

View file

@ -0,0 +1,36 @@
using System;
class Program
{
static void Main(string[] args)
{
int switchWins = 0;
int stayWins = 0;
Random gen = new Random();
for(int plays = 0; plays < 1000000; plays++ )
{
int[] doors = {0,0,0};//0 is a goat, 1 is a car
var winner = gen.Next(3);
doors[winner] = 1; //put a winner in a random door
int choice = gen.Next(3); //pick a door, any door
int shown; //the shown door
do
{
shown = gen.Next(3);
}
while (doors[shown] == 1 || shown == choice); //don't show the winner or the choice
stayWins += doors[choice]; //if you won by staying, count it
//the switched (last remaining) door is (3 - choice - shown), because 0+1+2=3
switchWins += doors[3 - choice - shown];
}
Console.Out.WriteLine("Staying wins " + stayWins + " times.");
Console.Out.WriteLine("Switching wins " + switchWins + " times.");
}
}

View file

@ -0,0 +1,31 @@
//Evidence of the Monty Hall solution of marquinho1986 in C [github.com/marquinho1986]
#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() {
unsigned long int i,stay=0;
int ChosenDoor,WinningDoor;
bool door[3]={0,0,0};
srand(time(NULL)); //initialize random seed.
for(i=0;i<=NumSim;i++){
WinningDoor=rand() % 3; // choosing winning door.
ChosenDoor=rand() % 3; // selected door.
if(door[WinningDoor]=true,door[ChosenDoor])stay++;
door[WinningDoor]=false;
}
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);
}

View file

@ -0,0 +1,89 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. monty-hall.
DATA DIVISION.
WORKING-STORAGE SECTION.
78 Num-Games VALUE 1000000.
*> These are needed so the values are passed to
*> get-rand-int correctly.
01 One PIC 9 VALUE 1.
01 Three PIC 9 VALUE 3.
01 doors-area.
03 doors PIC 9 OCCURS 3 TIMES.
01 choice PIC 9.
01 shown PIC 9.
01 winner PIC 9.
01 switch-wins PIC 9(7).
01 stay-wins PIC 9(7).
01 stay-wins-percent PIC Z9.99.
01 switch-wins-percent PIC Z9.99.
PROCEDURE DIVISION.
PERFORM Num-Games TIMES
MOVE 0 TO doors (winner)
CALL "get-rand-int" USING CONTENT One, Three,
REFERENCE winner
MOVE 1 TO doors (winner)
CALL "get-rand-int" USING CONTENT One, Three,
REFERENCE choice
PERFORM WITH TEST AFTER
UNTIL NOT(shown = winner OR choice)
CALL "get-rand-int" USING CONTENT One, Three,
REFERENCE shown
END-PERFORM
ADD doors (choice) TO stay-wins
ADD doors (6 - choice - shown) TO switch-wins
END-PERFORM
COMPUTE stay-wins-percent ROUNDED =
stay-wins / Num-Games * 100
COMPUTE switch-wins-percent ROUNDED =
switch-wins / Num-Games * 100
DISPLAY "Staying wins " stay-wins " times ("
stay-wins-percent "%)."
DISPLAY "Switching wins " switch-wins " times ("
switch-wins-percent "%)."
.
IDENTIFICATION DIVISION.
PROGRAM-ID. get-rand-int.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 call-flag PIC X VALUE "Y".
88 first-call VALUE "Y", FALSE "N".
01 num-range PIC 9.
LINKAGE SECTION.
01 min-num PIC 9.
01 max-num PIC 9.
01 ret PIC 9.
PROCEDURE DIVISION USING min-num, max-num, ret.
*> Seed RANDOM once.
IF first-call
MOVE FUNCTION RANDOM(FUNCTION CURRENT-DATE (9:8))
TO num-range
SET first-call TO FALSE
END-IF
COMPUTE num-range = max-num - min-num + 1
COMPUTE ret =
FUNCTION MOD(FUNCTION RANDOM * 100000, num-range)
+ min-num
.
END PROGRAM get-rand-int.
END PROGRAM monty-hall.

View file

@ -0,0 +1,51 @@
use Random;
param doors: int = 3;
config const games: int = 1000;
config const maxTasks = 32;
var numTasks = 1;
while( games / numTasks > 1000000 && numTasks < maxTasks ) do numTasks += 1;
const tasks = 1..#numTasks;
const games_per_task = games / numTasks ;
const remaining_games = games % numTasks ;
var wins_by_stay: [tasks] int;
coforall task in tasks {
var rand = new RandomStream();
for game in 1..#games_per_task {
var player_door = (rand.getNext() * 1000): int % doors ;
var winning_door = (rand.getNext() * 1000): int % doors ;
if player_door == winning_door then
wins_by_stay[ task ] += 1;
}
if task == tasks.last then {
for game in 1..#remaining_games {
var player_door = (rand.getNext() * 1000): int % doors ;
var winning_door = (rand.getNext() * 1000): int % doors ;
if player_door == winning_door then
wins_by_stay[ task ] += 1;
}
}
}
var total_by_stay = + reduce wins_by_stay;
var total_by_switch = games - total_by_stay;
var percent_by_stay = ((total_by_stay: real) / games) * 100;
var percent_by_switch = ((total_by_switch: real) / games) * 100;
writeln( "Wins by staying: ", total_by_stay, " or ", percent_by_stay, "%" );
writeln( "Wins by switching: ", total_by_switch, " or ", percent_by_switch, "%" );
if ( total_by_stay > total_by_switch ){
writeln( "Staying is the superior method." );
} else if( total_by_stay < total_by_switch ){
writeln( "Switching is the superior method." );
} else {
writeln( "Both methods are equal." );
}

View file

@ -0,0 +1,15 @@
(ns monty-hall-problem
(:use [clojure.contrib.seq :only (shuffle)]))
(defn play-game [staying]
(let [doors (shuffle [:goat :goat :car])
choice (rand-int 3)
[a b] (filter #(not= choice %) (range 3))
alternative (if (= :goat (nth doors a)) b a)]
(= :car (nth doors (if staying choice alternative)))))
(defn simulate [staying times]
(let [wins (reduce (fn [counter _] (if (play-game staying) (inc counter) counter))
0
(range times))]
(str "wins " wins " times out of " times)))

View file

@ -0,0 +1,6 @@
monty-hall-problem> (println "staying:" (simulate true 1000))
staying: wins 337 times out of 1000
nil
monty-hall-problem> (println "switching:" (simulate false 1000))
switching: wins 638 times out of 1000
nil

View file

@ -0,0 +1,42 @@
<cfscript>
function runmontyhall(num_tests) {
// number of wins when player switches after original selection
switch_wins = 0;
// number of wins when players "sticks" with original selection
stick_wins = 0;
// run all the tests
for(i=1;i<=num_tests;i++) {
// unconditioned potential for selection of each door
doors = [0,0,0];
// winning door is randomly assigned...
winner = randrange(1,3);
// ...and actualized in the array of real doors
doors[winner] = 1;
// player chooses one of three doors
choice = randrange(1,3);
do {
// monty randomly reveals a door...
shown = randrange(1,3);
}
// ...but monty only reveals empty doors;
// he will not reveal the door that the player has choosen
// nor will he reveal the winning door
while(shown==choice || doors[shown]==1);
// when the door the player originally selected is the winner, the "stick" option gains a point
stick_wins += doors[choice];
// to calculate the number of times the player would have won with a "switch", subtract the
// "value" of the chosen, "stuck-to" door from 1, the possible number of wins if the player
// chose and stuck with the winning door (1), the player would not have won by switching, so
// the value is 1-1=0 if the player chose and stuck with a losing door (0), the player would
// have won by switching, so the value is 1-0=1
switch_wins += 1-doors[choice];
}
// finally, simply run the percentages for each outcome
stick_percentage = (stick_wins/num_tests)*100;
switch_percentage = (switch_wins/num_tests)*100;
writeoutput('Number of Tests: ' & num_tests);
writeoutput('<br />Stick Wins: ' & stick_wins & ' ['& stick_percentage &'%]');
writeoutput('<br />Switch Wins: ' & switch_wins & ' ['& switch_percentage &'%]');
}
runmontyhall(10000);
</cfscript>

View file

@ -0,0 +1,15 @@
(defun make-round ()
(let ((array (make-array 3
:element-type 'bit
:initial-element 0)))
(setf (bit array (random 3)) 1)
array))
(defun show-goat (initial-choice array)
(loop for i = (random 3)
when (and (/= initial-choice i)
(zerop (bit array i)))
return i))
(defun won? (array i)
(= 1 (bit array i)))

View file

@ -0,0 +1,18 @@
CL-USER> (progn (loop repeat #1=(expt 10 6)
for round = (make-round)
for initial = (random 3)
for goat = (show-goat initial round)
for choice = (loop for i = (random 3)
when (and (/= i initial)
(/= i goat))
return i)
when (won? round (random 3))
sum 1 into result-stay
when (won? round choice)
sum 1 into result-switch
finally (progn (format t "Stay: ~S%~%" (float (/ result-stay
#1# 1/100)))
(format t "Switch: ~S%~%" (float (/ result-switch
#1# 1/100))))))
Stay: 33.2716%
Switch: 66.6593%

View file

@ -0,0 +1,14 @@
;Find out how often we win if we always switch
(defun rand-elt (s)
(elt s (random (length s))))
(defun monty ()
(let* ((doors '(0 1 2))
(prize (random 3));possible values: 0, 1, 2
(pick (random 3))
(opened (rand-elt (remove pick (remove prize doors))));monty opens a door which is not your pick and not the prize
(other (car (remove pick (remove opened doors))))) ;you decide to switch to the one other door that is not your pick and not opened
(= prize other))) ; did you switch to the prize?
(defun monty-trials (n)
(count t (loop for x from 1 to n collect (monty))))

View file

@ -0,0 +1,31 @@
import std.stdio, std.random;
void main() {
int switchWins, stayWins;
while (switchWins + stayWins < 100_000) {
immutable carPos = uniform(0, 3); // Which door is car behind?
immutable pickPos = uniform(0, 3); // Contestant's initial pick.
int openPos; // Which door is opened by Monty Hall?
// Monty can't open the door you picked or the one with the car
// behind it.
do {
openPos = uniform(0, 3);
} while(openPos == pickPos || openPos == carPos);
int switchPos;
// Find position that's not currently picked by contestant and
// was not opened by Monty already.
for (; pickPos==switchPos || openPos==switchPos; switchPos++) {}
if (pickPos == carPos)
stayWins++;
else if (switchPos == carPos)
switchWins++;
else
assert(0); // Can't happen.
}
writefln("Switching/Staying wins: %d %d", switchWins, stayWins);
}

View file

@ -0,0 +1,83 @@
int rand(int max) => (Math.random()*max).toInt();
class Game {
int _prize;
int _open;
int _chosen;
Game() {
_prize=rand(3);
_open=null;
_chosen=null;
}
void choose(int door) {
_chosen=door;
}
void reveal() {
if(_prize==_chosen) {
int toopen=rand(2);
if (toopen>=_prize)
toopen++;
_open=toopen;
} else {
for(int i=0;i<3;i++)
if(_prize!=i && _chosen!=i) {
_open=i;
break;
}
}
}
void change() {
for(int i=0;i<3;i++)
if(_chosen!=i && _open!=i) {
_chosen=i;
break;
}
}
bool hasWon() => _prize==_chosen;
String toString() {
String res="Prize is behind door $_prize";
if(_chosen!=null) res+=", player has chosen door $_chosen";
if(_open!=null) res+=", door $_open is open";
return res;
}
}
void play(int count, bool swap) {
int wins=0;
for(int i=0;i<count;i++) {
Game game=new Game();
game.choose(rand(3));
game.reveal();
if(swap)
game.change();
if(game.hasWon())
wins++;
}
String withWithout=swap?"with":"without";
double percent=(wins*100.0)/count;
print("playing $withWithout switching won $percent%");
}
test() {
for(int i=0;i<5;i++) {
Game g=new Game();
g.choose(i%3);
g.reveal();
print(g);
g.change();
print(g);
print("win==${g.hasWon()}");
}
}
main() {
play(10000,false);
play(10000,true);
}

View file

@ -0,0 +1,49 @@
program MontyHall;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
const
numGames = 1000000; // Number of games to run
var
switchWins, stayWins, plays: Int64;
doors: array[0..2] of Integer;
i, winner, choice, shown: Integer;
begin
switchWins := 0;
stayWins := 0;
for plays := 1 to numGames do
begin
//0 is a goat, 1 is a car
for i := 0 to 2 do
doors[i] := 0;
//put a winner in a random door
winner := Random(3);
doors[winner] := 1;
//pick a door, any door
choice := Random(3);
//don't show the winner or the choice
repeat
shown := Random(3);
until (doors[shown] <> 1) and (shown <> choice);
//if you won by staying, count it
stayWins := stayWins + doors[choice];
//the switched (last remaining) door is (3 - choice - shown), because 0+1+2=3
switchWins := switchWins + doors[3 - choice - shown];
end;
WriteLn('Staying wins ' + IntToStr(stayWins) + ' times.');
WriteLn('Switching wins ' + IntToStr(switchWins) + ' times.');
end.

View file

@ -0,0 +1,20 @@
var switchWins = 0
var stayWins = 0
for plays in 0..1000000 {
var doors = [0 ,0, 0]
var winner = rnd(max: 3)
doors[winner] = 1
var choice = rnd(max: 3)
var shown = rnd(max: 3)
while doors[shown] == 1 || shown == choice {
shown = rnd(max: 3)
}
stayWins += doors[choice]
switchWins += doors[3 - choice - shown]
}
print("Staying wins \(stayWins) times.")
print("Switching wins \(switchWins) times.")

View file

@ -0,0 +1,42 @@
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)

View file

@ -0,0 +1,313 @@
note
description: "[
Monty Hall Problem as an Eiffel Solution
1. Set the stage: Randomly place car and two goats behind doors 1, 2 and 3.
2. Monty offers choice of doors --> Contestant will choose a random door or always one door.
2a. Door has Goat - door remains closed
2b. Door has Car - door remains closed
3. Monty offers cash --> Contestant takes or refuses cash.
3a. Takes cash: Contestant is Cash winner and door is revealed. Car Loser if car door revealed.
3b. Refuses cash: Leads to offer to switch doors.
4. Monty offers door switch --> Contestant chooses to stay or change.
5. Door reveal: Contestant refused cash and did or did not door switch. Either way: Reveal!
6. Winner and Loser based on door reveal of prize.
Car Winner: Chooses car door
Cash Winner: Chooses cash over any door
Goat Loser: Chooses goat door
Car Loser: Chooses cash over car door or switches from car door to goat door
]"
date: "$Date$"
revision: "$Revision$"
class
MH_APPLICATION
create
make
feature {NONE} -- Initialization
make
-- Initialize Current.
do
play_lets_make_a_deal
ensure
played_1000_games: game_count = times_to_play
end
feature {NONE} -- Implementation: Access
live_contestant: attached like contestant
-- Attached version of `contestant'
do
if attached contestant as al_contestant then
Result := al_contestant
else
create Result
check not_attached_contestant: False end
end
end
contestant: detachable TUPLE [first_door_choice, second_door_choice: like door_number_anchor; takes_cash, switches_door: BOOLEAN]
-- Contestant for Current.
active_stage_door (a_door: like door_anchor): attached like door_anchor
-- Attached version of `a_door'.
do
if attached a_door as al_door then
Result := al_door
else
create Result
check not_attached_door: False end
end
end
door_1, door_2, door_3: like door_anchor
-- Doors with prize names and flags for goat and open (revealed).
feature {NONE} -- Implementation: Status
game_count, car_win_count, cash_win_count, car_loss_count, goat_loss_count, goat_avoidance_count: like counter_anchor
switch_count, switch_win_count: like counter_anchor
no_switch_count, no_switch_win_count: like counter_anchor
-- Counts of games played, wins and losses based on car, cash or goat.
feature {NONE} -- Implementation: Basic Operations
prepare_stage
-- Prepare the stage in terms of what doors have what prizes.
do
inspect new_random_of (3)
when 1 then
door_1 := door_with_car
door_2 := door_with_goat
door_3 := door_with_goat
when 2 then
door_1 := door_with_goat
door_2 := door_with_car
door_3 := door_with_goat
when 3 then
door_1 := door_with_goat
door_2 := door_with_goat
door_3 := door_with_car
end
active_stage_door (door_1).number := 1
active_stage_door (door_2).number := 2
active_stage_door (door_3).number := 3
ensure
door_has_prize: not active_stage_door (door_1).is_goat or
not active_stage_door (door_2).is_goat or
not active_stage_door (door_3).is_goat
consistent_door_numbers: active_stage_door (door_1).number = 1 and
active_stage_door (door_2).number = 2 and
active_stage_door (door_3).number = 3
end
door_number_having_prize: like door_number_anchor
-- What door number has the car?
do
if not active_stage_door (door_1).is_goat then
Result := 1
elseif not active_stage_door (door_2).is_goat then
Result := 2
elseif not active_stage_door (door_3).is_goat then
Result := 3
else
check prize_not_set: False end
end
ensure
one_to_three: between_1_and_x_inclusive (3, Result)
end
door_with_car: attached like door_anchor
-- Create a door with a car.
do
create Result
Result.name := prize
ensure
not_empty: not Result.name.is_empty
name_is_prize: Result.name.same_string (prize)
end
door_with_goat: attached like door_anchor
-- Create a door with a goat
do
create Result
Result.name := gag_gift
Result.is_goat := True
ensure
not_empty: not Result.name.is_empty
name_is_prize: Result.name.same_string (gag_gift)
is_gag_gift: Result.is_goat
end
next_contestant: attached like live_contestant
-- The next contestant on Let's Make a Deal!
do
create Result
Result.first_door_choice := new_random_of (3)
Result.second_door_choice := choose_another_door (Result.first_door_choice)
Result.takes_cash := random_true_or_false
if not Result.takes_cash then
Result.switches_door := random_true_or_false
end
ensure
choices_one_to_three: Result.first_door_choice <= 3 and Result.second_door_choice <= 3
switch_door_implies_no_cash_taken: Result.switches_door implies not Result.takes_cash
end
choose_another_door (a_first_choice: like door_number_anchor): like door_number_anchor
-- Make a choice from the remaining doors
require
one_to_three: between_1_and_x_inclusive (3, a_first_choice)
do
Result := new_random_of (3)
from until Result /= a_first_choice
loop
Result := new_random_of (3)
end
ensure
first_choice_not_second: a_first_choice /= Result
result_one_to_three: between_1_and_x_inclusive (3, Result)
end
play_lets_make_a_deal
-- Play the game 1000 times
local
l_car_win, l_car_loss, l_cash_win, l_goat_loss, l_goat_avoided: BOOLEAN
do
from
game_count := 0
invariant
consistent_win_loss_counts: (game_count = (car_win_count + cash_win_count + goat_loss_count))
consistent_loss_avoidance_counts: (game_count = (car_loss_count + goat_avoidance_count))
until
game_count >= times_to_play
loop
prepare_stage
contestant := next_contestant
l_cash_win := (live_contestant.takes_cash)
l_car_win := (not l_cash_win and
(not live_contestant.switches_door and live_contestant.first_door_choice = door_number_having_prize) or
(live_contestant.switches_door and live_contestant.second_door_choice = door_number_having_prize))
l_car_loss := (not live_contestant.switches_door and live_contestant.first_door_choice /= door_number_having_prize) or
(live_contestant.switches_door and live_contestant.second_door_choice /= door_number_having_prize)
l_goat_loss := (not l_car_win and not l_cash_win)
l_goat_avoided := (not live_contestant.switches_door and live_contestant.first_door_choice = door_number_having_prize) or
(live_contestant.switches_door and live_contestant.second_door_choice = door_number_having_prize)
check consistent_goats: l_goat_loss implies not l_goat_avoided end
check consistent_car_win: l_car_win implies not l_car_loss and not l_cash_win and not l_goat_loss end
check consistent_cash_win: l_cash_win implies not l_car_win and not l_goat_loss end
check consistent_goat_avoidance: l_goat_avoided implies (l_car_win or l_cash_win) and not l_goat_loss end
check consistent_car_loss: l_car_loss implies l_cash_win or l_goat_loss end
if l_car_win then car_win_count := car_win_count + 1 end
if l_cash_win then cash_win_count := cash_win_count + 1 end
if l_goat_loss then goat_loss_count := goat_loss_count + 1 end
if l_car_loss then car_loss_count := car_loss_count + 1 end
if l_goat_avoided then goat_avoidance_count := goat_avoidance_count + 1 end
if live_contestant.switches_door then
switch_count := switch_count + 1
if l_car_win then
switch_win_count := switch_win_count + 1
end
else -- if not live_contestant.takes_cash and not live_contestant.switches_door then
no_switch_count := no_switch_count + 1
if l_car_win or l_cash_win then
no_switch_win_count := no_switch_win_count + 1
end
end
game_count := game_count + 1
end
print ("%NCar Wins:%T%T " + car_win_count.out +
"%NCash Wins:%T%T " + cash_win_count.out +
"%NGoat Losses:%T%T " + goat_loss_count.out +
"%N-----------------------------" +
"%NTotal Win/Loss:%T%T" + (car_win_count + cash_win_count + goat_loss_count).out +
"%N%N" +
"%NCar Losses:%T%T " + car_loss_count.out +
"%NGoats Avoided:%T%T " + goat_avoidance_count.out +
"%N-----------------------------" +
"%NTotal Loss/Avoid:%T" + (car_loss_count + goat_avoidance_count).out +
"%N-----------------------------" +
"%NStaying Count/Win:%T" + no_switch_count.out + "/" + no_switch_win_count.out + " = " + (no_switch_win_count / no_switch_count * 100).out + " %%" +
"%NSwitch Count/Win:%T" + switch_count.out + "/" + switch_win_count.out + " = " + (switch_win_count / switch_count * 100).out + " %%"
)
end
feature {NONE} -- Implementation: Random Numbers
last_random: like random_number_anchor
-- The last random number chosen.
random_true_or_false: BOOLEAN
-- A randome True or False
do
Result := new_random_of (2) = 2
end
new_random_of (a_number: like random_number_anchor): like door_number_anchor
-- A random number from 1 to `a_number'.
do
Result := (new_random \\ a_number + 1).as_natural_8
end
new_random: like random_number_anchor
-- Random integer
-- Each call returns another random number.
do
random_sequence.forth
Result := random_sequence.item
last_random := Result
ensure
old_random_not_new: old last_random /= last_random
end
random_sequence: RANDOM
-- Random sequence seeded from clock when called.
attribute
create Result.set_seed ((create {TIME}.make_now).milli_second)
end
feature {NONE} -- Implementation: Constants
times_to_play: NATURAL_16 = 1000
-- Times to play the game.
prize: STRING = "Car"
-- Name of the prize
gag_gift: STRING = "Goat"
-- Name of the gag gift
door_anchor: detachable TUPLE [number: like door_number_anchor; name: STRING; is_goat, is_open: BOOLEAN]
-- Type anchor for door tuples.
door_number_anchor: NATURAL_8
-- Type anchor for door numbers.
random_number_anchor: INTEGER
-- Type anchor for random numbers.
counter_anchor: NATURAL_16
-- Type anchor for counters.
feature {NONE} -- Implementation: Contract Support
between_1_and_x_inclusive (a_number, a_value: like door_number_anchor): BOOLEAN
-- Is `a_value' between 1 and `a_number'?
do
Result := (a_value > 0) and (a_value <= a_number)
end
end

View file

@ -0,0 +1,23 @@
defmodule MontyHall do
def simulate(n) do
{stay, switch} = simulate(n, 0, 0)
:io.format "Staying wins ~w times (~.3f%)~n", [stay, 100 * stay / n]
:io.format "Switching wins ~w times (~.3f%)~n", [switch, 100 * switch / n]
end
defp simulate(0, stay, switch), do: {stay, switch}
defp simulate(n, stay, switch) do
doors = Enum.shuffle([:goat, :goat, :car])
guess = :rand.uniform(3) - 1
[choice] = [0,1,2] -- [guess, shown(doors, guess)]
if Enum.at(doors, choice) == :car, do: simulate(n-1, stay, switch+1),
else: simulate(n-1, stay+1, switch)
end
defp shown(doors, guess) do
[i, j] = Enum.shuffle([0,1,2] -- [guess])
if Enum.at(doors, i) == :goat, do: i, else: j
end
end
MontyHall.simulate(10000)

View file

@ -0,0 +1,15 @@
(defun montyhall (keep)
(let ((prize (random 3))
(choice (random 3)))
(if keep (= prize choice)
(/= prize choice))))
(let ((cnt 0))
(dotimes (i 10000)
(and (montyhall t) (setq cnt (1+ cnt))))
(message "Strategy keep: %.3f%%" (/ cnt 100.0)))
(let ((cnt 0))
(dotimes (i 10000)
(and (montyhall nil) (setq cnt (1+ cnt))))
(message "Strategy switch: %.3f%%" (/ cnt 100.0)))

View file

@ -0,0 +1,27 @@
-module(monty_hall).
-export([main/0]).
main() ->
random:seed(now()),
{WinStay, WinSwitch} = experiment(100000, 0, 0),
io:format("Switching wins ~p times.\n", [WinSwitch]),
io:format("Staying wins ~p times.\n", [WinStay]).
experiment(0, WinStay, WinSwitch) ->
{WinStay, WinSwitch};
experiment(N, WinStay, WinSwitch) ->
Doors = setelement(random:uniform(3), {0,0,0}, 1),
SelectedDoor = random:uniform(3),
OpenDoor = open_door(Doors, SelectedDoor),
experiment(
N - 1,
WinStay + element(SelectedDoor, Doors),
WinSwitch + element(6 - (SelectedDoor + OpenDoor), Doors) ).
open_door(Doors,SelectedDoor) ->
OpenDoor = random:uniform(3),
case (element(OpenDoor, Doors) =:= 1) or (OpenDoor =:= SelectedDoor) of
true -> open_door(Doors, SelectedDoor);
false -> OpenDoor
end.

View file

@ -0,0 +1,20 @@
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)

View file

@ -0,0 +1,13 @@
open System
let monty nSims =
let rnd = new Random()
let SwitchGame() =
let winner, pick = rnd.Next(0,3), rnd.Next(0,3)
if winner <> pick then 1 else 0
let StayGame() =
let winner, pick = rnd.Next(0,3), rnd.Next(0,3)
if winner = pick then 1 else 0
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

View file

@ -0,0 +1,32 @@
let montySlower nSims =
let rnd = new Random()
let MontyPick winner pick =
if pick = winner then
[0..2] |> Seq.filter (fun i -> i <> pick) |> Seq.nth (rnd.Next(0,2))
else
3 - pick - winner
let SwitchGame() =
let winner, pick = rnd.Next(0,3), rnd.Next(0,3)
let monty = MontyPick winner pick
let pickFinal = 3 - monty - pick
// Show that Monty's pick has no effect...
if (winner <> pick) <> (pickFinal = winner) then
printfn "Monty's selection actually had an effect!"
if pickFinal = winner then 1 else 0
let StayGame() =
let winner, pick = rnd.Next(0,3), rnd.Next(0,3)
let monty = MontyPick winner pick
// This one's even more obvious than the above since pickFinal
// is precisely the same as pick
let pickFinal = pick
if (winner = pick) <> (winner = pickFinal) then
printfn "Monty's selection actually had an effect!"
if winner = pickFinal then 1 else 0
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

View file

@ -0,0 +1,17 @@
include random.fs
variable stay-wins
variable switch-wins
: trial ( -- )
3 random 3 random ( prize choice )
= if 1 stay-wins +!
else 1 switch-wins +!
then ;
: trials ( n -- )
0 stay-wins ! 0 switch-wins !
dup 0 do trial loop
cr stay-wins @ . [char] / emit dup . ." staying wins"
cr switch-wins @ . [char] / emit . ." switching wins" ;
1000 trials

View file

@ -0,0 +1,14 @@
0 value stay-wins
0 value switch-wins
: trial ( -- )
3 choose 3 choose ( -- prize choice )
= IF 1 +TO stay-wins exit ENDIF
1 +TO switch-wins ;
: trials ( n -- )
CLEAR stay-wins
CLEAR switch-wins
dup 0 ?DO trial LOOP
CR stay-wins DEC. ." / " dup DEC. ." staying wins,"
CR switch-wins DEC. ." / " DEC. ." switching wins." ;

View file

@ -0,0 +1,29 @@
require random.fs
here seed !
1000000 constant rounds
variable wins
variable car
variable firstPick
variable revealed
defer applyStrategy
: isCar ( u - f ) car @ = ;
: remaining ( u u - u ) 3 swap - swap - ;
: setup 3 random car ! ;
: choose 3 random firstPick ! ;
: otherGoat ( - u ) car @ firstPick @ remaining ;
: randomGoat ( - u ) car @ 1+ 2 random + 3 mod ;
: reveal firstPick @ isCar IF randomGoat ELSE otherGoat THEN revealed ! ;
: keep ( - u ) firstPick @ ;
: switch ( - u ) firstPick @ revealed @ remaining ;
: open ( u - f ) isCar ;
: play ( - f ) setup choose reveal applyStrategy open ;
: record ( f ) 1 and wins +! ;
: run 0 wins ! rounds 0 ?DO play record LOOP ;
: result wins @ 0 d>f rounds 0 d>f f/ 100e f* ;
: .result result f. '%' emit ;
' keep IS applyStrategy run ." Keep door => " .result cr
' switch IS applyStrategy run ." Switch door => " .result cr
bye

View file

@ -0,0 +1,46 @@
PROGRAM MONTYHALL
IMPLICIT NONE
INTEGER, PARAMETER :: trials = 10000
INTEGER :: i, choice, prize, remaining, show, staycount = 0, switchcount = 0
LOGICAL :: door(3)
REAL :: rnum
CALL RANDOM_SEED
DO i = 1, trials
door = .FALSE.
CALL RANDOM_NUMBER(rnum)
prize = INT(3*rnum) + 1
door(prize) = .TRUE. ! place car behind random door
CALL RANDOM_NUMBER(rnum)
choice = INT(3*rnum) + 1 ! choose a door
DO
CALL RANDOM_NUMBER(rnum)
show = INT(3*rnum) + 1
IF (show /= choice .AND. show /= prize) EXIT ! Reveal a goat
END DO
SELECT CASE(choice+show) ! Calculate remaining door index
CASE(3)
remaining = 3
CASE(4)
remaining = 2
CASE(5)
remaining = 1
END SELECT
IF (door(choice)) THEN ! You win by staying with your original choice
staycount = staycount + 1
ELSE IF (door(remaining)) THEN ! You win by switching to other door
switchcount = switchcount + 1
END IF
END DO
WRITE(*, "(A,F6.2,A)") "Chance of winning by not switching is", real(staycount)/trials*100, "%"
WRITE(*, "(A,F6.2,A)") "Chance of winning by switching is", real(switchcount)/trials*100, "%"
END PROGRAM MONTYHALL

View file

@ -0,0 +1,35 @@
' 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

View file

@ -0,0 +1,27 @@
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
games := 100000
r := rand.New(rand.NewSource(time.Now().UnixNano()))
var switcherWins, keeperWins, shown int
for i := 0; i < games; i++ {
doors := []int{0, 0, 0}
doors[r.Intn(3)] = 1 // Set which one has the car
choice := r.Intn(3) // Choose a door
for shown = r.Intn(3); shown == choice || doors[shown] == 1; shown = r.Intn(3) {}
switcherWins += doors[3 - choice - shown]
keeperWins += doors[choice]
}
floatGames := float32(games)
fmt.Printf("Switcher Wins: %d (%3.2f%%)\n",
switcherWins, (float32(switcherWins) / floatGames * 100))
fmt.Printf("Keeper Wins: %d (%3.2f%%)",
keeperWins, (float32(keeperWins) / floatGames * 100))
}

View file

@ -0,0 +1,34 @@
import System.Random (StdGen, getStdGen, randomR)
trials :: Int
trials = 10000
data Door = Car | Goat deriving Eq
play :: Bool -> StdGen -> (Door, StdGen)
play switch g = (prize, new_g)
where (n, new_g) = randomR (0, 2) g
d1 = [Car, Goat, Goat] !! n
prize = case switch of
False -> d1
True -> case d1 of
Car -> Goat
Goat -> Car
cars :: Int -> Bool -> StdGen -> (Int, StdGen)
cars n switch g = f n (0, g)
where f 0 (cs, g) = (cs, g)
f n (cs, g) = f (n - 1) (cs + result, new_g)
where result = case prize of Car -> 1; Goat -> 0
(prize, new_g) = play switch g
main = do
g <- getStdGen
let (switch, g2) = cars trials True g
(stay, _) = cars trials False g2
putStrLn $ msg "switch" switch
putStrLn $ msg "stay" stay
where msg strat n = "The " ++ strat ++ " strategy succeeds " ++
percent n ++ "% of the time."
percent n = show $ round $
100 * (fromIntegral n) / (fromIntegral trials)

View file

@ -0,0 +1,21 @@
import Control.Monad.State
play :: Bool -> State StdGen Door
play switch = do
i <- rand
let d1 = [Car, Goat, Goat] !! i
return $ case switch of
False -> d1
True -> case d1 of
Car -> Goat
Goat -> Car
where rand = do
g <- get
let (v, new_g) = randomR (0, 2) g
put new_g
return v
cars :: Int -> Bool -> StdGen -> (Int, StdGen)
cars n switch g = (numcars, new_g)
where numcars = length $ filter (== Car) prize_list
(prize_list, new_g) = runState (replicateM n (play switch)) g

View file

@ -0,0 +1,2 @@
The switch strategy succeeds 67% of the time.
The stay strategy succeeds 34% of the time.

View file

@ -0,0 +1,32 @@
REAL :: ndoors=3, doors(ndoors), plays=1E4
DLG(NameEdit = plays, DNum=1, Button='Go')
switchWins = 0
stayWins = 0
DO play = 1, plays
doors = 0 ! clear the doors
winner = 1 + INT(RAN(ndoors)) ! door that has the prize
doors(winner) = 1
guess = 1 + INT(RAN(doors)) ! player chooses his door
IF( guess == winner ) THEN ! Monty decides which door to open:
show = 1 + INT(RAN(2)) ! select 1st or 2nd goat-door
checked = 0
DO check = 1, ndoors
checked = checked + (doors(check) == 0)
IF(checked == show) open = check
ENDDO
ELSE
open = (1+2+3) - winner - guess
ENDIF
new_guess_if_switch = (1+2+3) - guess - open
stayWins = stayWins + doors(guess) ! count if guess was correct
switchWins = switchWins + doors(new_guess_if_switch)
ENDDO
WRITE(ClipBoard, Name) plays, switchWins, stayWins
END

View file

@ -0,0 +1,4 @@
! plays=1E3; switchWins=695; stayWins=305;
! plays=1E4; switchWins=6673; stayWins=3327;
! plays=1E5; switchWins=66811; stayWins=33189;
! plays=1E6; switchWins=667167; stayWins=332833;

View file

@ -0,0 +1,15 @@
100 PROGRAM "MontyH.bas"
110 RANDOMIZE
120 LET NUMGAMES=1000
130 LET CHANGING,NOTCHANGING=0
140 FOR I=0 TO NUMGAMES-1
150 LET PRIZEDOOR=RND(3)+1:LET CHOSENDOOR=RND(3)+1
160 IF CHOSENDOOR=PRIZEDOOR THEN
170 LET NOTCHANGING=NOTCHANGING+1
180 ELSE
190 LET CHANGING=CHANGING+1
200 END IF
210 NEXT
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."

View file

@ -0,0 +1,19 @@
procedure main(arglist)
rounds := integer(arglist[1]) | 10000
doors := '123'
strategy1 := strategy2 := 0
every 1 to rounds do {
goats := doors -- ( car := ?doors )
guess1 := ?doors
show := goats -- guess1
if guess1 == car then strategy1 +:= 1
else strategy2 +:= 1
}
write("Monty Hall simulation for ", rounds, " rounds.")
write("Strategy 1 'Staying' won ", real(strategy1) / rounds )
write("Strategy 2 'Switching' won ", real(strategy2) / rounds )
end

View file

@ -0,0 +1,22 @@
keepWins := 0
switchWins := 0
doors := 3
times := 100000
pickDoor := method(excludeA, excludeB,
door := excludeA
while(door == excludeA or door == excludeB,
door = (Random value() * doors) floor
)
door
)
times repeat(
playerChoice := pickDoor()
carDoor := pickDoor()
shownDoor := pickDoor(carDoor, playerChoice)
switchDoor := pickDoor(playerChoice, shownDoor)
(playerChoice == carDoor) ifTrue(keepWins = keepWins + 1)
(switchDoor == carDoor) ifTrue(switchWins = switchWins + 1)
)
("Switching to the other door won #{switchWins} times.\n"\
.. "Keeping the same door won #{keepWins} times.\n"\
.. "Game played #{times} times with #{doors} doors.") interpolate println

View file

@ -0,0 +1 @@
pick=: {~ ?@#

View file

@ -0,0 +1 @@
DOORS=:1 2 3

View file

@ -0,0 +1 @@
scenario=: ((pick@-.,])pick,pick) bind DOORS

View file

@ -0,0 +1 @@
stayWin=: =/@}.

View file

@ -0,0 +1 @@
switchWin=: pick@(DOORS -. }:) = {:

View file

@ -0,0 +1,2 @@
+/ (stayWin,switchWin)@scenario"0 i.1000
320 680

View file

@ -0,0 +1,11 @@
simulate=:3 :0
1 2 3 simulate y
:
pick=. {~ ?@#
scenario=. ((pick@-.,])pick,pick) bind x
stayWin=. =/@}.
switchWin=. pick@(x -. }:) = {:
r=.(stayWin,switchWin)@scenario"0 i.y
labels=. ];.2 'limit stay switch '
smoutput labels,.":"0 y,+/r
)

View file

@ -0,0 +1,4 @@
simulate 1000
limit 1000
stay 304
switch 696

View file

@ -0,0 +1,4 @@
1 2 3 4 simulate 1000
limit 1000
stay 233
switch 388

View file

@ -0,0 +1,25 @@
import java.util.Random;
public class Monty{
public static void main(String[] args){
int switchWins = 0;
int stayWins = 0;
Random gen = new Random();
for(int plays = 0;plays < 32768;plays++ ){
int[] doors = {0,0,0};//0 is a goat, 1 is a car
doors[gen.nextInt(3)] = 1;//put a winner in a random door
int choice = gen.nextInt(3); //pick a door, any door
int shown; //the shown door
do{
shown = gen.nextInt(3);
//don't show the winner or the choice
}while(doors[shown] == 1 || shown == choice);
stayWins += doors[choice];//if you won by staying, count it
//the switched (last remaining) door is (3 - choice - shown), because 0+1+2=3
switchWins += doors[3 - choice - shown];
}
System.out.println("Switching wins " + switchWins + " times.");
System.out.println("Staying wins " + stayWins + " times.");
}
}

View file

@ -0,0 +1,38 @@
function montyhall(tests, doors) {
'use strict';
tests = tests ? tests : 1000;
doors = doors ? doors : 3;
var prizeDoor, chosenDoor, shownDoor, switchDoor, chosenWins = 0, switchWins = 0;
// randomly pick a door excluding input doors
function pick(excludeA, excludeB) {
var door;
do {
door = Math.floor(Math.random() * doors);
} while (door === excludeA || door === excludeB);
return door;
}
// run tests
for (var i = 0; i < tests; i ++) {
// pick set of doors
prizeDoor = pick();
chosenDoor = pick();
shownDoor = pick(prizeDoor, chosenDoor);
switchDoor = pick(chosenDoor, shownDoor);
// test set for both choices
if (chosenDoor === prizeDoor) {
chosenWins ++;
} else if (switchDoor === prizeDoor) {
switchWins ++;
}
}
// results
return {
stayWins: chosenWins + ' ' + (100 * chosenWins / tests) + '%',
switchWins: switchWins + ' ' + (100 * switchWins / tests) + '%'
};
}

View file

@ -0,0 +1,6 @@
montyhall(1000, 3)
Object {stayWins: "349 34.9%", switchWins: "651 65.1%"}
montyhall(1000, 4)
Object {stayWins: "253 25.3%", switchWins: "384 38.4%"}
montyhall(1000, 5)
Object {stayWins: "202 20.2%", switchWins: "265 26.5%"}

View file

@ -0,0 +1,49 @@
<html>
<body>
<input id="userInputMH" value="1000">
<input id="userInputDoor" value="3">
<br>
<button onclick="montyhall()">Calculate</button>
<p id="firstPickWins"></p>
<p id="switchPickWins"></p>
</body>
</html>
<script>
function montyhall() {
var tests = document.getElementById("userInputMH").value;
var doors = document.getElementById("userInputDoor").value;
var prizeDoor, chosenDoor, shownDoor, switchDoor, chosenWins = 0,switchWins = 0;
function pick(excludeA, excludeB) {
var door;
do {
door = Math.floor(Math.random() * doors);
} while (door === excludeA || door === excludeB);
return door;
}
for (var i = 0; i < tests; i++) {
prizeDoor = pick();
chosenDoor = pick();
shownDoor = pick(prizeDoor, chosenDoor);
switchDoor = pick(chosenDoor, shownDoor);
if (chosenDoor === prizeDoor) {
chosenWins++;
} else if (switchDoor === prizeDoor) {
switchWins++;
}
}
document.getElementById("firstPickWins").innerHTML = 'First Door Wins: ' + chosenWins + ' | ' + (100 * chosenWins / tests) + '%';
document.getElementById("switchPickWins").innerHTML = 'Switched Door Wins: ' + switchWins + ' | ' + (100 * switchWins / tests) + '%';
}
</script>

View file

@ -0,0 +1,3 @@
(1000, 3)
First Door Wins: 346 | 34.6%
Switching Door Wins: 654 | 65.4%

View file

@ -0,0 +1,44 @@
var totalGames = 10000,
selectDoor = function () {
return Math.floor(Math.random() * 3); // Choose a number from 0, 1 and 2.
},
games = (function () {
var i = 0, games = [];
for (; i < totalGames; ++i) {
games.push(selectDoor()); // Pick a door which will hide the prize.
}
return games;
}()),
play = function (switchDoor) {
var i = 0, j = games.length, winningDoor, randomGuess, totalTimesWon = 0;
for (; i < j; ++i) {
winningDoor = games[i];
randomGuess = selectDoor();
if ((randomGuess === winningDoor && !switchDoor) ||
(randomGuess !== winningDoor && switchDoor))
{
/*
* 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.
*
* I lose when I initially guess the winning door and then switch,
* or initially guess a losing door and don't switch.
*/
totalTimesWon++;
}
}
return totalTimesWon;
};
/*
* Start the simulation
*/
console.log("Playing " + totalGames + " games");
console.log("Wins when not switching door", play(false));
console.log("Wins when switching door", play(true));

View file

@ -0,0 +1,3 @@
Playing 10000 games
Wins when not switching door 3326
Wins when switching door 6630

View file

@ -0,0 +1,18 @@
def rand:
input as $r
| if $r < . then $r else rand end;
def logical_montyHall:
. as $games
| {switchWins: 0, stayWins: 0}
| reduce range (0; $games) as $_ (.;
(3|rand) as $car # put car in a random door
| (3|rand) as $choice # choose a door at random
| if $choice == $car then .stayWins += 1
else .switchWins += 1
end )
| "Simulating \($games) games:",
"Staying wins \(.stayWins) times",
"Switching wins \(.switchWins) times\n" ;
1e3, 1e6 | logical_montyHall

View file

@ -0,0 +1,26 @@
def rand:
input as $r
| if $r < . then $r else rand end;
def montyHall:
. as $games
| [range(0;3) | 0 ] as $doors0
| {switchWins: 0, stayWins: 0}
| reduce range (0; $games) as $_ (.;
($doors0 | .[3|rand] = 1) as $doors # put car in a random door
| (3|rand) as $choice # choose a door at random
| .stop = false
| until (.stop;
.shown = (3|rand) # the shown door
| if ($doors[.shown] != 1 and .shown != $choice)
then .stop=true
else .
end)
| .stayWins += $doors[$choice]
| .switchWins += $doors[3 - $choice - .shown]
)
| "Simulating \($games) games:",
"Staying wins \(.stayWins) times",
"Switching wins \(.switchWins) times\n" ;
1e3, 1e6 | montyHall

View file

@ -0,0 +1,22 @@
using Printf
function play_mh_literal{T<:Integer}(ncur::T=3, ncar::T=1)
ncar < ncur || throw(DomainError())
curtains = shuffle(collect(1:ncur))
cars = curtains[1:ncar]
goats = curtains[(ncar+1):end]
pick = rand(1:ncur)
isstickwin = pick in cars
deleteat!(curtains, findin(curtains, pick))
if !isstickwin
deleteat!(goats, findin(goats, pick))
end
if length(goats) > 0 # reveal goat
deleteat!(curtains, findin(curtains, shuffle(goats)[1]))
else # no goats, so reveal car
deleteat!(curtains, rand(1:(ncur-1)))
end
pick = shuffle(curtains)[1]
isswitchwin = pick in cars
return (isstickwin, isswitchwin)
end

View file

@ -0,0 +1,11 @@
function play_mh_clean{T<:Integer}(ncur::T=3, ncar::T=1)
ncar < ncur || throw(DomainError())
pick = rand(1:ncur)
isstickwin = pick <= ncar
pick = rand(1:(ncur-2))
if isstickwin # remove initially picked car from consideration
pick += 1
end
isswitchwin = pick <= ncar
return (isstickwin, isswitchwin)
end

View file

@ -0,0 +1,44 @@
function mh_results{T<:Integer}(ncur::T, ncar::T,
nruns::T, play_mh::Function)
stickwins = 0
switchwins = 0
for i in 1:nruns
(isstickwin, isswitchwin) = play_mh(ncur, ncar)
if isstickwin
stickwins += 1
end
if isswitchwin
switchwins += 1
end
end
return (stickwins/nruns, switchwins/nruns)
end
function mh_analytic{T<:Integer}(ncur::T, ncar::T)
stickodds = ncar/ncur
switchodds = (ncar - stickodds)/(ncur-2)
return (stickodds, switchodds)
end
function show_odds{T<:Real}(a::T, b::T)
@sprintf " %.1f %.1f %.2f" 100.0*a 100*b 1.0*b/a
end
function show_simulation{T<:Integer}(ncur::T, ncar::T, nruns::T)
println()
print("Simulating a ", ncur, " door, ", ncar, " car ")
println("Monty Hall problem with ", nruns, " runs.\n")
println(" Solution Stick Switch Improvement")
(a, b) = mh_results(ncur, ncar, nruns, play_mh_literal)
println(@sprintf("%10s: ", "Literal"), show_odds(a, b))
(a, b) = mh_results(ncur, ncar, nruns, play_mh_clean)
println(@sprintf("%10s: ", "Clean"), show_odds(a, b))
(a, b) = mh_analytic(ncur, ncar)
println(@sprintf("%10s: ", "Analytic"), show_odds(a, b))
println()
return nothing
end

View file

@ -0,0 +1,3 @@
for i in 3:5, j in 1:(i-2)
show_simulation(i, j, 10^5)
end

View file

@ -0,0 +1,28 @@
// version 1.1.2
import java.util.Random
fun montyHall(games: Int) {
var switchWins = 0
var stayWins = 0
val rnd = Random()
(1..games).forEach {
val doors = IntArray(3) // all zero (goats) by default
doors[rnd.nextInt(3)] = 1 // put car in a random door
val choice = rnd.nextInt(3) // choose a door at random
var shown: Int
do {
shown = rnd.nextInt(3) // the shown door
}
while (doors[shown] == 1 || shown == choice)
stayWins += doors[choice]
switchWins += doors[3 - choice - shown]
}
println("Simulating $games games:")
println("Staying wins $stayWins times")
println("Switching wins $switchWins times")
}
fun main(args: Array<String>) {
montyHall(1_000_000)
}

View file

@ -0,0 +1,25 @@
'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."

View file

@ -0,0 +1,17 @@
function playgame(player)
local car = math.random(3)
local pchoice = player.choice()
local function neither(a, b) --slow, but it works
local el = math.random(3)
return (el ~= a and el ~= b) and el or neither(a, b)
end
local el = neither(car, pchoice)
if(player.switch) then pchoice = neither(pchoice, el) end
player.wins = player.wins + (pchoice == car and 1 or 0)
end
for _, v in ipairs{true, false} do
player = {choice = function() return math.random(3) end,
wins = 0, switch = v}
for i = 1, 20000 do playgame(player) end
print(player.wins)
end

View file

@ -0,0 +1,44 @@
Module CheckIt {
Enum Strat {Stay, Random, Switch}
total=10000
Print $("0.00")
player_win_stay=0
player_win_switch=0
player_win_random=0
For i=1 to total {
Dim doors(1 to 3)=False
doors(Random(1,3))=True
guess=Random(1,3)
Inventory other
for k=1 to 3 {
If k <> guess Then Append other, k
}
If doors(guess) Then {
Mont_Hall_show=other(Random(0,1)!)
} Else {
If doors(other(0!)) Then {
Mont_Hall_show=other(1!)
} Else Mont_Hall_show=other(0!)
Delete Other, Mont_Hall_show
}
Strategy=Each(Strat)
While Strategy {
Select Case Eval(strategy)
Case Random
{
If Random(1,2)=1 Then {
If doors(guess) Then player_win_Random++
} else If doors(other(0!)) Then player_win_Random++
}
Case Switch
If doors(other(0!)) Then player_win_switch++
Else
If doors(guess) Then player_win_stay++
End Select
}
}
Print "Stay: ";player_win_stay/total*100;"%"
Print "Random: ";player_win_Random/total*100;"%"
Print "Switch: ";player_win_switch/total*100;"%"
}
CheckIt

View file

@ -0,0 +1,56 @@
function montyHall(numDoors,numSimulations)
assert(numDoors > 2);
function num = randInt(n)
num = floor( n*rand()+1 );
end
%The first column will tallie wins, the second losses
switchedDoors = [0 0];
stayed = [0 0];
for i = (1:numSimulations)
availableDoors = (1:numDoors); %Preallocate the available doors
winningDoor = randInt(numDoors); %Define the winning door
playersOriginalChoice = randInt(numDoors); %The player picks his initial choice
availableDoors(playersOriginalChoice) = []; %Remove the players choice from the available doors
%Pick the door to open from the available doors
openDoor = availableDoors(randperm(numel(availableDoors))); %Sort the available doors randomly
openDoor(openDoor == winningDoor) = []; %Make sure Monty doesn't open the winning door
openDoor = openDoor(randInt(numel(openDoor))); %Choose a random door to open
availableDoors(availableDoors==openDoor) = []; %Remove the open door from the available doors
availableDoors(end+1) = playersOriginalChoice; %Put the player's original choice back into the pool of available doors
availableDoors = sort(availableDoors);
playersNewChoice = availableDoors(randInt(numel(availableDoors))); %Pick one of the available doors
if playersNewChoice == playersOriginalChoice
switch playersNewChoice == winningDoor
case true
stayed(1) = stayed(1) + 1;
case false
stayed(2) = stayed(2) + 1;
otherwise
error 'ERROR'
end
else
switch playersNewChoice == winningDoor
case true
switchedDoors(1) = switchedDoors(1) + 1;
case false
switchedDoors(2) = switchedDoors(2) + 1;
otherwise
error 'ERROR'
end
end
end
disp(sprintf('Switch win percentage: %f%%\nStay win percentage: %f%%\n', [switchedDoors(1)/sum(switchedDoors),stayed(1)/sum(stayed)] * 100));
end

View file

@ -0,0 +1,3 @@
>> montyHall(3,100000)
Switch win percentage: 66.705972%
Stay win percentage: 33.420062%

View file

@ -0,0 +1,25 @@
fn montyHall choice switch =
(
doors = #(false, false, false)
doors[random 1 3] = true
chosen = doors[choice]
if switch then chosen = not chosen
chosen
)
fn iterate iterations switched =
(
wins = 0
for i in 1 to iterations do
(
if (montyHall (random 1 3) switched) then
(
wins += 1
)
)
wins * 100 / iterations as float
)
iterations = 10000
format ("Stay strategy:%\%\n") (iterate iterations false)
format ("Switch strategy:%\%\n") (iterate iterations true)

View file

@ -0,0 +1,2 @@
Stay strategy:33.77%
Switch strategy:66.84%

View file

@ -0,0 +1,10 @@
montyHall[nGames_] :=
Module[{r, winningDoors, firstChoices, nStayWins, nSwitchWins, s},
r := RandomInteger[{1, 3}, nGames];
winningDoors = r;
firstChoices = r;
nStayWins = Count[Transpose[{winningDoors, firstChoices}], {d_, d_}];
nSwitchWins = nGames - nStayWins;
Grid[{{"Strategy", "Wins", "Win %"}, {"Stay", Row[{nStayWins, "/", nGames}], s=N[100 nStayWins/nGames]},
{"Switch", Row[{nSwitchWins, "/", nGames}], 100 - s}}, Frame -> All]]

View file

@ -0,0 +1 @@
montyHall[100000]

View file

@ -0,0 +1,35 @@
/* NetRexx ************************************************************
* 30.08.2013 Walter Pachl translated from Java/REXX/PL/I
**********************************************************************/
options replace format comments java crossref savelog symbols nobinary
doors = create_doors
switchWins = 0
stayWins = 0
shown=0
Loop plays=1 To 1000000
doors=0
r=r3()
doors[r]=1
choice = r3()
loop Until shown<>choice & doors[shown]=0
shown = r3()
End
If doors[choice]=1 Then
stayWins=stayWins+1
Else
switchWins=switchWins+1
End
Say "Switching wins " switchWins " times."
Say "Staying wins " stayWins " times."
method create_doors static returns Rexx
doors = ''
doors[0] = 0
doors[1] = 0
doors[2] = 0
return doors
method r3 static
rand=random()
return rand.nextInt(3) + 1

View file

@ -0,0 +1,38 @@
import random
randomize()
proc shuffle[T](x: var seq[T]) =
for i in countdown(x.high, 0):
let j = rand(i)
swap(x[i], x[j])
# 1 represents a car
# 0 represent a goat
var
stay = 0 # amount won if stay in the same position
switch = 0 # amount won if you switch
for i in 1..1000:
var lst = @[1,0,0] # one car and two goats
shuffle(lst) # shuffles the list randomly
let ran = rand(2 ) # gets a random number for the random guess
let user = lst[ran] # storing the random guess
del lst, ran # deleting the random guess
var huh = 0
for i in lst: # getting a value 0 and deleting it
if i == 0:
del lst, huh # deletes a goat when it finds it
break
inc huh
if user == 1: # if the original choice is 1 then stay adds 1
inc stay
if lst[0] == 1: # if the switched value is 1 then switch adds 1
inc switch
echo "Stay = ",stay
echo "Switch = ",switch

View file

@ -0,0 +1,29 @@
let trials = 10000
type door = Car | Goat
let play switch =
let n = Random.int 3 in
let d1 = [|Car; Goat; Goat|].(n) in
if not switch then d1
else match d1 with
Car -> Goat
| Goat -> Car
let cars n switch =
let total = ref 0 in
for i = 1 to n do
let prize = play switch in
if prize = Car then
incr total
done;
!total
let () =
let switch = cars trials true
and stay = cars trials false in
let msg strat n =
Printf.printf "The %s strategy succeeds %f%% of the time.\n"
strat (100. *. (float n /. float trials)) in
msg "switch" switch;
msg "stay" stay

View file

@ -0,0 +1,13 @@
test(trials)={
my(stay=0,change=0);
for(i=1,trials,
my(prize=random(3),initial=random(3),opened);
while((opened=random(3))==prize | opened==initial,);
if(prize == initial, stay++, change++)
);
print("Wins when staying: "stay);
print("Wins when changing: "change);
[stay, change]
};
test(1e4)

View file

@ -0,0 +1,27 @@
<?php
function montyhall($iterations){
$switch_win = 0;
$stay_win = 0;
foreach (range(1, $iterations) as $i){
$doors = array(0, 0, 0);
$doors[array_rand($doors)] = 1;
$choice = array_rand($doors);
do {
$shown = array_rand($doors);
} while($shown == $choice || $doors[$shown] == 1);
$stay_win += $doors[$choice];
$switch_win += $doors[3 - $choice - $shown];
}
$stay_percentages = ($stay_win/$iterations)*100;
$switch_percentages = ($switch_win/$iterations)*100;
echo "Iterations: {$iterations} - ";
echo "Stayed wins: {$stay_win} ({$stay_percentages}%) - ";
echo "Switched wins: {$switch_win} ({$switch_percentages}%)";
}
montyhall(10000);
?>

View file

@ -0,0 +1,38 @@
*process source attributes xref;
ziegen: Proc Options(main);
/* REXX ***************************************************************
* 30.08.2013 Walter Pachl derived from Java
**********************************************************************/
Dcl (switchWins,stayWins) Bin Fixed(31) Init(0);
Dcl doors(3) Bin Fixed(31);
Dcl (plays,r,choice) Bin Fixed(31) Init(0);
Dcl c17 Char(17) Init((datetime()));
Dcl p9 Pic'(9)9' def(c17) pos(5);
i=random(p9);
Do plays=1 To 1000000;
doors=0;
r=r3();
doors(r)=1;
choice=r3();
Do Until(shown^=choice & doors(shown)=0);
shown=r3();
End;
If doors(choice)=1 Then
stayWins+=1;
Else
switchWins+=1;
End;
Put Edit("Switching wins ",switchWins," times.")(Skip,a,f(6),a);
Put Edit("Staying wins ",stayWins ," times.")(Skip,a,f(6),a);
r3: Procedure Returns(Bin Fixed(31));
/*********************************************************************
* Return a random integer: 1, 2, or 3
*********************************************************************/
Dcl r Bin Float(53);
Dcl res Bin Fixed(31);
r=random();
res=(r*3)+1;
Return(res);
End;
End;

View file

@ -0,0 +1,50 @@
program MontyHall;
uses
sysutils;
const
NumGames = 1000;
{Randomly pick a door(a number between 0 and 2}
function PickDoor(): Integer;
begin
Exit(Trunc(Random * 3));
end;
var
i: Integer;
PrizeDoor: Integer;
ChosenDoor: Integer;
WinsChangingDoors: Integer = 0;
WinsNotChangingDoors: Integer = 0;
begin
Randomize;
for i := 0 to NumGames - 1 do
begin
//randomly picks the prize door
PrizeDoor := PickDoor;
//randomly chooses a door
ChosenDoor := PickDoor;
//if the strategy is not changing doors the only way to win is if the chosen
//door is the one with the prize
if ChosenDoor = PrizeDoor then
Inc(WinsNotChangingDoors);
//if the strategy is changing doors the only way to win is if we choose one
//of the two doors that hasn't the prize, because when we change we change to the prize door.
//The opened door doesn't have a prize
if ChosenDoor <> PrizeDoor then
Inc(WinsChangingDoors);
end;
Writeln('Num of games:' + IntToStr(NumGames));
Writeln('Wins not changing doors:' + IntToStr(WinsNotChangingDoors) + ', ' +
FloatToStr((WinsNotChangingDoors / NumGames) * 100) + '% of total.');
Writeln('Wins changing doors:' + IntToStr(WinsChangingDoors) + ', ' +
FloatToStr((WinsChangingDoors / NumGames) * 100) + '% of total.');
end.

View file

@ -0,0 +1,27 @@
#! /usr/bin/perl
use strict;
my $trials = 10000;
my $stay = 0;
my $switch = 0;
foreach (1 .. $trials)
{
my $prize = int(rand 3);
# let monty randomly choose a door where he puts the prize
my $chosen = int(rand 3);
# let us randomly choose a door...
my $show;
do { $show = int(rand 3) } while $show == $chosen || $show == $prize;
# ^ monty opens a door which is not the one with the
# prize, that he knows it is the one the player chosen
$stay++ if $prize == $chosen;
# ^ if player chose the correct door, player wins only if he stays
$switch++ if $prize == 3 - $chosen - $show;
# ^ if player switches, the door he picks is (3 - $chosen - $show),
# because 0+1+2=3, and he picks the only remaining door that is
# neither $chosen nor $show
}
print "Stay win ratio " . (100.0 * $stay/$trials) . "\n";
print "Switch win ratio " . (100.0 * $switch/$trials) . "\n";

View file

@ -0,0 +1,18 @@
(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>
<span style="color: #004080;">atom</span> <span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">game</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">1_000_000</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">winner</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">choice</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">reveal</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">reveal</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">winner</span> <span style="color: #008080;">and</span> <span style="color: #000000;">reveal</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">choice</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #000000;">stayWins</span> <span style="color: #0000FF;">+=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">choice</span><span style="color: #0000FF;">==</span><span style="color: #000000;">winner</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">other</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">6</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: #000080;font-style:italic;">-- (as 1+2+3=6, and reveal!=choice)</span>
<span style="color: #000000;">swapWins</span> <span style="color: #0000FF;">+=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">other</span><span style="color: #0000FF;">==</span><span style="color: #000000;">winner</span><span style="color: #0000FF;">)</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>
<!--

View file

@ -0,0 +1,29 @@
go =>
_ = random2(), % different seed
member(Rounds,[1000,10_000,100_000,1_000_000,10_000_000]),
println(rounds=Rounds),
SwitchWins = 0,
StayWins = 0,
NumDoors = 3,
foreach(_ in 1..Rounds)
Winner = choice(NumDoors),
Choice = choice(NumDoors),
% Shown is not needed for the simulation
% Shown = pick([Door : Door in 1..NumDoors, Door != Winner, Door != Choice]),
if Choice == Winner then
StayWins := StayWins + 1
else
SwitchWins := SwitchWins + 1
end
end,
printf("Switch win ratio %0.5f%%\n", 100.0 * SwitchWins/Rounds),
printf("Stay win ratio %0.5f%%\n", 100.0 * StayWins/Rounds),
nl,
fail,
nl.
% pick a number from 1..N
choice(N) = random(1,N).
pick(L) = L[random(1,L.len)].

View file

@ -0,0 +1,19 @@
(de montyHall (Keep)
(let (Prize (rand 1 3) Choice (rand 1 3))
(if Keep # Keeping the first choice?
(= Prize Choice) # Yes: Monty's choice doesn't matter
(<> Prize Choice) ) ) ) # Else: Win if your first choice was wrong
(prinl
"Strategy KEEP -> "
(let Cnt 0
(do 10000 (and (montyHall T) (inc 'Cnt)))
(format Cnt 2) )
" %" )
(prinl
"Strategy SWITCH -> "
(let Cnt 0
(do 10000 (and (montyHall NIL) (inc 'Cnt)))
(format Cnt 2) )
" %" )

View file

@ -0,0 +1,36 @@
%!PS
/Courier % name the desired font
20 selectfont % choose the size in points and establish
% the font as the current one
% init random number generator
(%Calendar%) currentdevparams /Second get srand
1000000 % iteration count
0 0 % 0 wins on first selection 0 wins on switch
2 index % get iteration count
{
rand 3 mod % winning door
rand 3 mod % first choice
eq {
1 add
}
{
exch 1 add exch
} ifelse
} repeat
% compute percentages
2 index div 100 mul exch 2 index div 100 mul
% display result
70 600 moveto
(Switching the door: ) show
80 string cvs show (%) show
70 700 moveto
(Keeping the same: ) show
80 string cvs show (%) show
showpage % print all on the page

View file

@ -0,0 +1,54 @@
#Declaring variables
$intIterations = 10000
$intKept = 0
$intSwitched = 0
#Creating a function
Function Play-MontyHall()
{
#Using a .NET object for randomization
$objRandom = New-Object -TypeName System.Random
#Generating the winning door number
$intWin = $objRandom.Next(1,4)
#Generating the chosen door
$intChoice = $objRandom.Next(1,4)
#Generating the excluded number
#Because there is no method to exclude a number from a range,
#I let it re-generate in case it equals the winning number or
#in case it equals the chosen door.
$intLose = $objRandom.Next(1,4)
While (($intLose -EQ $intWin) -OR ($intLose -EQ $intChoice))
{$intLose = $objRandom.Next(1,4)}
#Generating the 'other' door
#Same logic applies as for the chosen door: it cannot be equal
#to the winning door nor to the chosen door.
$intSwitch = $objRandom.Next(1,4)
While (($intSwitch -EQ $intLose) -OR ($intSwitch -EQ $intChoice))
{$intSwitch = $objRandom.Next(1,4)}
#Simple counters per win for both categories
#Because a child scope cannot change variables in the parent
#scope, the scope of the counters is expanded script-wide.
If ($intChoice -EQ $intWin)
{$script:intKept++}
If ($intSwitch -EQ $intWin)
{$script:intSwitched++}
}
#Looping the Monty Hall function for $intIterations times
While ($intIterationCount -LT $intIterations)
{
Play-MontyHall
$intIterationCount++
}
#Output
Write-Host "Results through $intIterations iterations:"
Write-Host "Keep : $intKept ($($intKept/$intIterations*100)%)"
Write-Host "Switch: $intSwitched ($($intSwitched/$intIterations*100)%)"
Write-Host ""

View file

@ -0,0 +1,43 @@
:- initialization(main).
% Simulate a play.
play(Switch, Won) :-
% Random prize door
random(1, 4, P),
% Random contestant door
random(1, 4, C),
% Random reveal door, not prize or contestant door
repeat,
random(1, 4, R),
R \= P,
R \= C,
!,
% Final door
(
Switch, between(1, 3, F), F \= C, F \= R, !;
\+ Switch, F = C
),
% Check result.
(F = P -> Won = true ; Won = false).
% Count wins.
win_count(0, _, Total, Total).
win_count(I, Switch, A, Total) :-
I > 0,
I1 is I - 1,
play(Switch, Won),
(Won, A1 is A + 1;
\+ Won, A1 is A),
win_count(I1, Switch, A1, Total).
main :-
randomize,
win_count(1000, true, 0, SwitchTotal),
format('Switching wins ~d out of 1000.\n', [SwitchTotal]),
win_count(1000, false, 0, StayTotal),
format('Staying wins ~d out of 1000.\n', [StayTotal]).

View file

@ -0,0 +1,35 @@
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()

View file

@ -0,0 +1,45 @@
'''
I could understand the explanation of the Monty Hall problem
but needed some more evidence
References:
http://www.bbc.co.uk/dna/h2g2/A1054306
http://en.wikipedia.org/wiki/Monty_Hall_problem especially:
http://en.wikipedia.org/wiki/Monty_Hall_problem#Increasing_the_number_of_doors
'''
from random import randrange
doors, iterations = 3,100000 # could try 100,1000
def monty_hall(choice, switch=False, doorCount=doors):
# Set up doors
door = [False]*doorCount
# One door with prize
door[randrange(doorCount)] = True
chosen = door[choice]
unpicked = door
del unpicked[choice]
# Out of those unpicked, the alternative is either:
# the prize door, or
# an empty door if the initial choice is actually the prize.
alternative = True in unpicked
if switch:
return alternative
else:
return chosen
print "\nMonty Hall problem simulation:"
print doors, "doors,", iterations, "iterations.\n"
print "Not switching allows you to win",
print sum(monty_hall(randrange(3), switch=False)
for x in range(iterations)),
print "out of", iterations, "times."
print "Switching allows you to win",
print sum(monty_hall(randrange(3), switch=True)
for x in range(iterations)),
print "out of", iterations, "times.\n"

Some files were not shown because too many files have changed in this diff Show more