#!/your/perl/here
# DND dice stats
# give expected value for $dice_num, with $dice_sides, dropping the lowest $dice_drop die.
use strict;
use warnings;
our $dice_num = ( shift or 4 );
our $dice_side = ( shift or 6 );
our $dice_drop = ( @ARGV ? shift : 1 );
our $total;
our $count;
foreach my $index ( 0 .. ( $dice_side**$dice_num ) - 1 )
{
use integer;
my @digits;
foreach my $digit ( 0 .. $dice_num - 1 )
{
$digits[$digit] = ( $index / ( $dice_side ** $digit ) ) % $dice_side + 1;
}
my $sum;
foreach my $die ( ( sort @digits )[$dice_drop..$dice_num-1] )
{
$sum += $die;
}
$total += $sum;
$count++;
# use this for intermediate results
# print "(@digits) sum=$sum, t=$total, c=$count\n";
}
our $avg = $total/$count;
print "${dice_num}d${dice_side}-${dice_drop}: $total/$count=$avg\n";
__END__
####
>dnd.pl 4 6
4d6-1: 15869/1296=12.2445987654321
####
>dnd.pl 2 6 0
2d6-0: 252/36=7