#!/usr/bin/perl

sub sign_significance {
    my ($trials, $hits, $probability) = @_;
    my $confidence;
    foreach ($hits..$trials) {
        $confidence += binomial($trials, $hits, $probability);
    }
    return $confidence;
}

if (sign_significance(8, 6, 0.5) <= 0.05) {
    print "The left link is more popular. \n";
} else {
    print "Insufficient data to conclude that the left link is more popular. \n";
}

# $prob = binomial($n, $k, $p)
#    Return the probability of an event occurring $k times,
#    in $n attempts, where the probability of it occurring
#    in a single attempt is $p.
sub binomial {
    my ($n, $k, $p) = @_;

    return $k == 0 if $p == 0;
    return $k != $n if $p == 1;
    return choose($n, $k) * $p**$k * (1-$p)**($n-$k);
}

# choose($n, $k) is the number of ways to choose $k elements from a set
# of $n elements, when the order of selection is irrelevant.
#
sub choose {
    my ($n, $k) = @_;
    my ($result, $j) = (1, 1);

    return 0 if $k > $n || $k < 0;
    $k = ($n - $k) if ($n - $k) < $k;

    while ( $j <= $k ) {
        $result *= $n--;
        $result /= $j++;
    }
    return $result;
}

sub choose_simple {
    my ($n, $k) = @_;
    return permutation($n,$k) / permutation($n-$k);
}

