#!/usr/bin/perl -w use strict; use Algorithm::Loops qw(NestedLoops); use List::Util qw(sum); #Set no. of elements, frequencies and the sum value my $nElements = 2; my @freq = qw (0.1 0.2 0.7); my $targetSum = 4; #Ways of generating sum given no. of elements my @pos = (0..$#freq); my (@combo, @matrix); for my $c (0..$nElements-1) { push @combo, [@pos]; } my @nest = NestedLoops(\@combo, sub { [ @_ ] } ); for my $n (0..$#nest) { push @{$matrix[sum @{$nest[$n]}]}, join ('', @{$nest[$n]}); } my @ways = @{$matrix[$targetSum]}; #Now calculate P-value my @pVal; foreach my $w (0..$#ways) { my @f = split ('', $ways[$w]); #print "@f\n"; my $p = $freq[$f[0]]; #print $p,"\n"; for my $g (1..$#f) { $p *= $freq[$f[$g]]; } push @pVal, $p; } my $pVal = sum @pVal; print "P-value(sum of $nElements = $targetSum) = $pVal\n"; #Prints: P-value(sum of 2 = 4) = 0.49