Re: Sort of OT: Dice odds Message #9 Posted by Thomas Klemm on 12 Sept 2011, 3:34 p.m., in response to message #1 by Dave Britten
Quote:
What are the odds of rolling a total of 17 or greater using four standard 6-sided dice?
There's a function glob in Perl that does the cross joins. For example, this produces nine strings, one for each pairing of fruits and colors:
@many = glob "{apple,tomato,cherry}={green,yellow,red}";
That's the program I came up with:
#!/usr/bin/perl
use strict;
use warnings;
my $dice = '+{1,2,3,4,5,6}';
my $n = 4;
my %seen;
for my $roll (glob $dice x $n) {
my $sum = eval $roll;
$seen{$sum}++;
};
my $total = 0;
for my $value (sort { $a <=> $b } keys %seen) {
printf <<EOF, $value, $seen{$value};
%4d %6d
EOF
$total += $seen{$value} if 17 <= $value;
}
printf <<EOF, $total, $total/6**$n;
Total = %d (%.5f)
EOF
And that's the result it produces when the script is started with time:
4 1
5 4
6 10
7 20
8 35
9 56
10 80
11 104
12 125
13 140
14 146
15 140
16 125
17 104
18 80
19 56
20 35
21 20
22 10
23 4
24 1
Total = 310 (0.23920)
real 0m0.032s
user 0m0.029s
sys 0m0.002s
I hope it is useful and you can modify it to your needs. It's not optimized for speed (the function eval is used often), but for small n it might be fast enough.
Kind regards
Thomas
Edited: 12 Sept 2011, 5:14 p.m.
|