Created
March 2, 2011 02:20
-
-
Save hjst/850343 to your computer and use it in GitHub Desktop.
This file contains 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/env perl | |
sub toss( $ ); # prints coin toss results for $ coins | |
if( !defined($ARGV[0]) ) | |
{ | |
# If there was no command line argument | |
print "Number of coins not specified - using default number: 3\n\n"; | |
toss( 3 ); | |
} | |
else | |
{ | |
print "Tossing $ARGV[0] coins:\n\n"; | |
toss( $ARGV[0] ); | |
} | |
print "======================================\n"; | |
print " Heads = $heads\n"; | |
print " Tails = $tails\n\n"; | |
if( $heads > $tails ) | |
{ | |
$diff = $heads - $tails; | |
print "Heads wins (by $diff).\n"; | |
} | |
elsif( $tails > $heads ) | |
{ | |
$diff = $tails - $heads; | |
print "Tails wins (by $diff).\n"; | |
} | |
else | |
{ | |
print "Draw. Tossing the decider...\n"; | |
toss( 1 ); | |
} | |
sub toss( $ ) | |
{ | |
$heads = $tails = 0; | |
$coin_limit = $_[0]; | |
for( $i = 0; $i < $coin_limit; $i++ ) | |
{ | |
# rand() function returns a value between 0 and 1 | |
# including 0, but excluding 1. The random seed is time(). | |
$x = rand( ); | |
if( $x >= 0.5 ) { $heads++; printf "%20.30f >= 0.5 : Heads\n", $x; } | |
if( $x < 0.5 ) { $tails++; printf "%20.30f < 0.5 : Tails\n", $x; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment