Created
June 1, 2013 01:33
-
-
Save benclark/5688967 to your computer and use it in GitHub Desktop.
Montyhall
This file contains hidden or 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/perl -w | |
use strict; | |
use warnings; | |
sub automatic_choice { | |
my ($n, $i, $j, $c, $u, $d, $t); | |
my ($win, $guess, $switch); | |
print STDERR "How many doors? [ > 1 ]: "; | |
$n = int(<STDIN>); | |
print STDERR "How many iterations? [ > 1 ]: "; | |
$j = int(<STDIN>); | |
print "user#\tcar#\tswitch?\twin?\n"; | |
for ($i = 0; $i < $j; $i++) { | |
$c = int(rand($n)) + 1; | |
$u = int(rand($n)) + 1; | |
$d = $c; | |
if ($u == $c) { | |
$guess++; | |
while ($d == $c) { | |
$d = int(rand($n)) + 1; | |
} | |
} | |
$t = 1; # (rand() >= .5) ? 1 : 0; | |
if ($t > 0) { | |
$switch++; | |
$u = $d; | |
} | |
print "$u\t$c\t$t\t"; | |
if ($u == $c) { | |
$win++; | |
print "1"; | |
} else { | |
print "0"; | |
} | |
print "\n"; | |
} | |
print "Total:\tWin\tLoss\tSwitches\n" . | |
"\t$win\t" . ($j - $win) . "\t$switch\n"; | |
} | |
sub manual_choice { | |
my ($n, $c, $u, $d, $t); | |
$n = 100; | |
$c = int(rand($n)) + 1; | |
print "There are $n doors, and a car behind one of them.\n" . | |
"Which door to pick? [1..$n]: "; | |
$u = int(<STDIN>); | |
# If user selected car.. | |
if ($u == $c) { | |
# .. then pick some other door to keep. | |
while ($d == $c) { $d = int(rand($n)) + 1; } | |
} else { | |
# .. else pick the car. | |
$d = $c; | |
} | |
print "Car is behind the remaining door or your choice, door $u. Change? [y,n]: "; | |
$t = <STDIN>; | |
if ($t =~ /[yY].*/) { | |
print "You switched to door $d.\n"; | |
$u = $d; | |
} | |
if ($u == $c) { | |
print "You won a car.\n"; | |
} else { | |
print "You got nothing. NOTHING.\n"; | |
} | |
} | |
sub main { | |
#manual_choice(); | |
automatic_choice(); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment