Created
January 25, 2023 09:52
-
-
Save Ovid/68a6b1e3c4b49fd42e9070bcc84e1742 to your computer and use it in GitHub Desktop.
Monty Carlo Problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
# See also: https://fosstodon.org/@ovid/109745522656272671 | |
# See also: https://priceonomics.com/the-time-everyone-corrected-the-worlds-smartest/ | |
use Less::Boilerplate; | |
# $does_switch = 0 means they don't switch doors | |
# $does_switch = 1 means they do switch doors | |
my $does_switch = 0; | |
my ( $win, $lose ) = ( 0, 0 ); | |
my $trials = 10_000; | |
for ( 1 .. $trials ) { | |
my $prize = int( rand(3) ); | |
my $choice = int( rand(3) ); | |
my @other_doors = grep { $_ != $choice } 0 .. 2; | |
my $revealed | |
= $prize == $other_doors[0] ? pop @other_doors | |
: $prize == $other_doors[1] ? shift @other_doors | |
: rand > .5 ? shift @other_doors | |
: pop @other_doors; | |
my $new_choice = $does_switch ? shift @other_doors : $choice; | |
( $new_choice == $prize ) ? $win++ : $lose++; | |
} | |
say sprintf "Win %% if you %s switch: %.1f%%." => | |
( $does_switch ? 'do' : 'do not' ), ( $win * 100 ) / $trials; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Okay then, if you prefer...