Skip to content

Instantly share code, notes, and snippets.

@hjst
Created Mar 2, 2011
Embed
What would you like to do?
#! /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