-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy path100_prisoners_riddle.pl
More file actions
51 lines (36 loc) · 914 Bytes
/
100_prisoners_riddle.pl
File metadata and controls
51 lines (36 loc) · 914 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/perl
# Simulation of the 100 Prisoners Riddle.
# See also the Veritasium video on this problem:
# https://yewtu.be/watch?v=iSNsgj1OCLA
use 5.014;
use strict;
use warnings;
use List::Util qw(shuffle);
my $ok = 0;
my $runs = 10000;
my $prisoners = 100;
for my $n (1 .. $runs) {
my @boxes = shuffle(0 .. $prisoners - 1);
my $success = 1;
foreach my $k (0 .. $prisoners - 1) {
my $found = 0;
my $pick = $boxes[$k];
for (my $tries = $prisoners >> 1 ; $tries > 0 ; --$tries) {
if ($pick == $k) {
$found = 1;
last;
}
$pick = $boxes[$pick];
}
if (not $found) {
$success = 0;
last;
}
}
if ($success) {
++$ok;
}
}
say "Probability of success: ", ($ok / $runs * 100), '%';
__END__
Probability of success: 31.52%