
BillKSmith
Veteran
Oct 31, 2011, 1:17 PM
Post #2 of 2
(77781 views)
|
The function new_dieRoll is equivalent to your dieRoll. I have used the module Test::More to show that is the same for all the test cases you supplied and a few more that I made up.
#!/usr/bin/perl use strict; use Test::More qw( no_plan); sub dieRoll { my ($drInValue, $drOutValue); my ($drMult, $drDie, $drOper, $drAddVal, $drHold); $drInValue = $_[0]; ($drHold, $drAddVal) = split(/[\+\-]/, $drInValue); ($drMult, $drDie) = split(/[dD]/, $drHold); for ($drMult; $drMult >= 1; $drMult--) { $drOutValue += int(rand()*$drDie) + 1; } if ($drInValue =~ /\+/) { $drOutValue += $drAddVal; } if ($drInValue =~ /\-/) { $drOutValue -= $drAddVal; } return $drOutValue; } sub new_dieRoll { my ($drMult, $drDie, $drAddVal) = $_[0] =~ m/(\d+)[Dd](\d+)([-+]\d+)/; my $drOutValue = $drAddVal + $drMult ; $drOutValue += int( rand $drDie ) for (1..$drMult); return $drOutValue; } #...begin my $count = 0; for ( $count = 5; $count >= 1; $count-- ) { my $RollTheDice = "4d10+5"; my $seed = rand(1000000); my $expected = do { srand $seed; dieRoll($RollTheDice) } ; my $new = do { srand $seed; new_dieRoll($RollTheDice) } ; is( $new, $expected, $RollTheDice ); } my @Rolls = ( '4d10-5', '4d12-5', '3d10+4', ); for my $Roll (@Rolls) { my $seed = rand(1000000); my $expected = do { srand $seed; dieRoll($Roll) } ; my $new = do { srand $seed; new_dieRoll($Roll) } ; is( $new, $expected, $Roll ); } Note: Parsing the input with a regular expression rather than split takes less code, no temporary variables, and it preserves the sign of drAddVal. Good Luck, Bill
|