Here is the code I wrote after reading the problem:
#!/usr/bin/perl -w use strict; srand; my $numtimes = 6; for ( my $rollattempt = 0 ; $rollattempt < $numtimes ; $rollattempt++ ) { my $numdice = 4; my $numsides = 6; my $sumof = 3; my $highest = 1; my @excludes = (1); print( "Roll attempt: ", $rollattempt, "\n", "\t", "Sum: ", &exclude_and_sum( $numdice, $numsides, $sumof, $highest, @excludes ), "\n" ); } sub exclude_and_sum { my ( $nd, $ns, $so, $high, @excl ) = @_; my @droll = (); my @temproll = (); my $sum = 0; for ( my $dice = 0 ; $dice < $nd ; $dice++ ) { push ( @droll, int( rand($ns) + 1 ) ); } @temproll = sort(@droll); @droll = (); while ( my $d = pop (@temproll) ) { $d = int( rand($ns) + 1 ) if ( scalar( grep( $d, @excl ) ) ); push ( @droll, $d ); } if ($high) { @droll = sort(@droll); } else { @droll = sort( { $b <=> $a } @droll ); } for ( my $count = 0 ; $count < $so ; $count++ ) { $sum += pop (@droll); } return ($sum); }
My output looked like:
Roll attempt: 0
	Sum: 12
Roll attempt: 1
	Sum: 10
Roll attempt: 2
	Sum: 10
Roll attempt: 3
	Sum: 11
Roll attempt: 4
	Sum: 9
Roll attempt: 5
	Sum: 12

As I envision it, this code (barring any unforeseen logic errors) should allow an array of excluded numbers to be set, and allow for the number of values in the sum, the number and sides of the dice, and which numbers (highest or lowest) to be in the sum to be easily selectable. However, I can't guarantee this code free of errors in logic, so please comment if you see any. And, as always, I look forward to the comments of others, so we may each our wisdom increase.


In reply to Re: Trick die rolling by atcroft
in thread Trick die rolling by ellem

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.