I decided to generalize in a different direction, show how you could use a few different programming ideas with this one. Feel free to play around with different sizes, numbers, and choices of die to throw. People who want to play should consider things like using GD::Graph to start producing bar charts etc.
#! /usr/bin/perl -w use strict; my @dist = dice_distribution( sides => 6, number => 4, slice => [1, 2, 3], ); my $average = sum( map $_*$dist[$_], 0..$#dist ) / sum(@dist); print "The average is $average\n"; sub dice_distribution { my %args = @_; my $sides = $args{sides} || 6; my $number = $args{number} || 3; my $slice = $args{slice} || [0..($number - 1)]; my @distribution; nested_for( sub { my @dice = (sort {$a <=> $b} @_)[@$slice]; $distribution[ sum(@dice) ]++; }, map [1..$sides], 1..$number, ); # Quiet warnings $_ ||= 0 for @distribution; return @distribution; } sub sum { my $sum = 0; $sum += $_ for @_; return $sum; } sub nested_for { bind_loops(@_)->(); } sub bind_loops { my $fn = shift; my $range = shift; my $sub = sub {$fn->($_, @_) for @$range}; return @_ ? bind_loops($sub, @_) : $sub; }
Admittedly I didn't make it shorter. But then again, as pointed out in The path to mastery, I don't think that shorter should always be the immediate aim of someone who is trying to learn...

(Yes, a key part of this bears a suspicious resemblance to Re (tilly) 1 (perl): What Happened...(perils of porting from c). If you are puzzled over how this works, figuring out that first may be a good idea.)


In reply to Re: Rolling DND Dice. by tilly
in thread Rolling DND Dice. by grendelkhan

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.