It's funny that when people "tackle" the Monty Hall problem with a program, they tend to write one that uses a simulation, running thousands (if not more) of test runs. And that while it's easy to brute-force it, as there are at most 108 cases to examine (3 places for the main prices, 3 initial picks, 2 possible doors for Monty to pick, switch/not-switch).
use 5.010;
my @doors = (1 .. 3);
my $switch_wins = 0;
my $switch_losses = 0;
my $noswitch_wins = 0;
my $noswitch_losses = 0;
#
# Place a price
#
foreach my $price (@doors) {
#
# Pick a door
#
foreach my $pick (@doors) {
#
# Monty's pick
#
my @monty_choices = grep {$_ != $price && $_ != $pick} @doors;
foreach my $monty_pick (@monty_choices) {
#
# Switch or not?
#
foreach my $switch (0, 1) {
#
# If switching, find final door
#
my $final_pick;
if ($switch) {
($final_pick) =
grep {$_ != $pick && $_ != $monty_pick} @doors;
}
else {
$final_pick = $pick;
}
my $prob = 1 / @monty_choices;
if ($switch) {
$switch_wins += $prob if $final_pick == $price;
$switch_losses += $prob if $final_pick != $price;
}
else {
$noswitch_wins += $prob if $final_pick == $price;
$noswitch_losses += $prob if $final_pick != $price
+;
}
}
}
}
}
printf "Switching: win percentage = %.2f%%\n",
100 * $switch_wins / ($switch_wins + $switch_losses);
printf "No switching: win percentage = %.2f%%\n",
100 * $noswitch_wins / ($noswitch_wins + $noswitch_losses);
__END__
Switching: win percentage = 66.67%
No switching: win percentage = 33.33%
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|