#!/usr/bin/perl
# Produces a random variable distributed according to the
# Discrete Binomial Probability Distribution with p, n, reps user input.
#
# This pretty much follows the definition of a random Binomial variable
# by calculating the number of successes in n trials with probability p.
# Execution time increases in proportion to n.
#
# Also see Journal of the ACM, Feb 1988, Vol 31, No. 3
# "Binomial Random Variate Generation" by Khachitvichyanukul and Schemeiser
# R. Winters 10/9/07
#

my $p = $ARGV[0];
my $n = $ARGV[1];
my $reps = $ARGV[2];

if ($p eq "" || $n eq "" || $reps eq "") {
    print "Usage: binomVar.pl prob trials reps<return>\n"; exit -1; }

srand (time() ^ ($$ + ($$ << 15)) );  # Random Seed

for (my $i=0;$i<$reps;$i++)
{
    print &binomvar($p, $n),"\n";
}
exit 0;

sub binomvar
{
    my $r = 0, $x = 0, $k = 0;
    if ( @_[0] < 0 || @_[0] > 1.0 ) { return 0; }
  do
    {
    $r = rand 1;
    $k++;  # trials
    if ( $r <= @_[0] ) { $x++; } # successes
} until ($k == int @_[1]);

    return $x;
}
