in reply to Re^2: Proving Veritasiums riddle using Perl
in thread Proving Veritasiums riddle using Perl

Cool program. It's much faster using a shuffle.

Your code:

% time perl prisoners-orig.pl == SIMULATION 9900 of 10000 == Success: 3085 Fail: 6915 Fail rate: 69.15% perl prisoners-orig.pl 13.09s user 0.01s system 99% cpu 13.101 total

Modified to use Array::Shuffle:

% time perl prisoners.pl == SIMULATION 9900 of 10000 == Success: 3175 Fail: 6825 Fail rate: 68.25% perl prisoners.pl 0.71s user 0.00s system 99% cpu 0.716 total

Diff:

--- prisoners-orig.pl 2025-04-30 17:24:41.190188166 -0400 +++ prisoners.pl 2025-04-30 17:24:01.156228637 -0400 @@ -7,7 +7,7 @@ use warnings; use diagnostics; -use Array::Contains; +use Array::Shuffle qw(shuffle_array); my $PRISONERCOUNT = 100; # How many prisoners my $OPENBOXES = $PRISONERCOUNT / 2; # Every prisoner can open half th +e boxes @@ -49,15 +49,8 @@ sub generateBoxes { print "Generating boxes...\n" if($DEBUG); - my @boxes; - - while(scalar @boxes < $PRISONERCOUNT) { - my $prisoner = int(rand($PRISONERCOUNT)); - if(!contains($prisoner, \@boxes)) { - push @boxes, $prisoner; - } - } - + my @boxes = (0..$PRISONERCOUNT-1); + shuffle_array(@boxes); return \@boxes; }
90% of every Perl application is already written.
dragonchild