Psst.. new poll here.
Psst.. new forums here.
Microsoft is blocking us again (TY IP Reputation!) so just use oauth login instead. :)
Paste
Pasted as Perl by registered user Dragon ( 16 years ago )
#!perl
use strict;
use warnings;
my %counter;
#bags are represented by an array.
#marbles are represented by strings describing their colour
{my @bag = (["red", "red"],
["red", "black"],
["black", "black"]);
sub random_bag {
my $choice = rand();
if ($choice < 0.33333) {return $bag[0];}
elsif ($choice < 0.66667) {return $bag[1];}
else {return $bag[2];}}}
#The next function picks a random bag then removes the first marble
#colour from the array if the random function returns a value lower
#than 0.5, else the second marble colour is removed. The colour of
#this marble is then concatened with the colour of the remaining
#marble, thus forming a key for a hash-value, which is then increased
#by 1.
sub random_marbles {
my @marble = @{random_bag()};
if (rand() < 0.5){
$counter{ shift(@marble).$marble[0] }++}
else {
$counter{ pop (@marble).$marble[0] }++}}
my $experiments = 0;
EXPERIMENT: while ($experiments < 10000) {
random_marbles();
next EXPERIMENT}
continue {
$experiments++;}
print "In $counter{\"redred\"} cases both the first as well as the second marble were red \n";
print "In $counter{\"redblack\"} cases the second marble was black while the first one was red \n";
print "In $counter{\"blackred\"} cases the second marble was red while the first one was black \n";
print "In $counter{\"blackblack\"} cases both the first as well as the second marble were black. \n";
print "In ", $counter{"redred"}/($counter{"redred"}+$counter{"redblack"}) * 100, "% of the cases, the 2nd marble was red if the first one was red. \n";
Revise this Paste
Parent: 19276