use 5.010; use strict; use warnings; use List::Util 'sum'; my @props = (0.05, 0.1, 0.2, 0.3); push @props, 1 - sum @props; # Make sure we sum to 1. my @THROWS = (5, 10, 25); my @values = (1, 5, 7, 13, 17, 23, 31, 43, 59, 91, 119); my %cache; sub chance; sub chance { my $throws = shift; my $target = shift; return $cache{$throws, $target} if defined $cache{$throws, $target}; return $cache{$throws, $target} = 0 if $throws < 1 || $target < $throws; if ($throws == 1) { return $cache{$throws, $target} = 0 if $target > @props; return $cache{$throws, $target} = $props[$target-1]; } return $cache{$throws, $target} = sum map {$props[$_-1] * chance $throws-1, $target-$_} 1 .. $#props; } my $start = sum times; foreach my $throws (@THROWS) { foreach my $value (@values) { say "Chance of hitting $value in $throws throws: ", chance $throws, $value; } } my $end = sum times; say "Running time: ", 1000 * ($end - $start), " milli-seconds"; __END__ Chance of rolling 1 in 5 throws: 0 Chance of rolling 5 in 5 throws: 3.125e-07 Chance of rolling 7 in 5 throws: 1.875e-05 Chance of rolling 13 in 5 throws: 0.00968 Chance of rolling 17 in 5 throws: 0.031295 Chance of rolling 23 in 5 throws: 0 Chance of rolling 31 in 5 throws: 0 Chance of rolling 43 in 5 throws: 0 Chance of rolling 59 in 5 throws: 0 Chance of rolling 91 in 5 throws: 0 Chance of rolling 119 in 5 throws: 0 Chance of rolling 1 in 10 throws: 0 Chance of rolling 5 in 10 throws: 0 Chance of rolling 7 in 10 throws: 0 Chance of rolling 13 in 10 throws: 1.69921875e-10 Chance of rolling 17 in 10 throws: 1.014837890625e-07 Chance of rolling 23 in 10 throws: 5.2156428125e-05 Chance of rolling 31 in 10 throws: 0.00234761235 Chance of rolling 43 in 10 throws: 0 Chance of rolling 59 in 10 throws: 0 Chance of rolling 91 in 10 throws: 0 Chance of rolling 119 in 10 throws: 0 Chance of rolling 1 in 25 throws: 0 Chance of rolling 5 in 25 throws: 0 Chance of rolling 7 in 25 throws: 0 Chance of rolling 13 in 25 throws: 0 Chance of rolling 17 in 25 throws: 0 Chance of rolling 23 in 25 throws: 0 Chance of rolling 31 in 25 throws: 1.08633041381835938e-25 Chance of rolling 43 in 25 throws: 7.92373889330642701e-17 Chance of rolling 59 in 25 throws: 9.08413811215993471e-10 Chance of rolling 91 in 25 throws: 1.16278186292830531e-07 Chance of rolling 119 in 25 throws: 0 Running time: 90 milli-seconds