My output looked like:#!/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); }
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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |