Skip to content

Instantly share code, notes, and snippets.

@DanGough
Last active September 18, 2019 23:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DanGough/ec56ec2a8a964968af8020371ba7b1a9 to your computer and use it in GitHub Desktop.
Save DanGough/ec56ec2a8a964968af8020371ba7b1a9 to your computer and use it in GitHub Desktop.
Function Play-Game {
param ([bool]$Swap)
$Doors = 1,2,3
$PrizeDoor = Get-Random $Doors
$MyDoor = Get-Random $Doors
[array]$RemovableDoors = $Doors | Where {$_ -ne $MyDoor -and $_ -ne $PrizeDoor}
$RemovedDoor = Get-Random $RemovableDoors
$RemainingDoor = $Doors | Where {$_ -ne $MyDoor -and $_ -ne $RemovedDoor}
If ($Swap) {
$MyDoor = $RemainingDoor
}
If ($MyDoor -eq $PrizeDoor) {
$Win = $true
}
Else {
$Win = $false
}
$Win
}
$NumberOfGames = 1000
$StickWins = 0
$SwapWins = 0
for ($i = 0; $i -lt $NumberOfGames; $i++) {
$Win = Play-Game -Swap $false
If ($Win) {
$StickWins++
}
$Win = Play-Game -Swap $true
If ($Win) {
$SwapWins++
}
}
$StickRatio = $StickWins / $NumberOfGames
$SwapRatio = $SwapWins / $NumberOfGames
Write-Output "Ratio of wins when sticking: $StickRatio"
Write-Output "Ratio of wins when swapping: $SwapRatio"
Read-Host -Prompt "Press enter to continue..."
@DanGough
Copy link
Author

DanGough commented Sep 18, 2019

Save as a .ps1 file. On Windows, view the file properties and unblock the file, then right-click and select 'Run with PowerShell' on Windows.

Or, open Powershell, cd into the correct location and run:

.\MontyHall.ps1

To run PowerShell on Mac/Linux, install it then run pwsh in the terminal.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment