in reply to calculating cribbage points
Well, other people have talked about how to do loops, or use modules to assist in the problem. I'm going to take an approach which is more customized to the specific application. Even so, it wouldn't be hard to extend if, for example, you started playing 7-card cribbage. :-)
sub sum { my $sum; $sum += $_ for @_; $sum } my @combos = map { my @v = reverse split //, sprintf "%05b", $_; my @w = grep { $v[$_] } 0 .. $#v; @w > 1 ? \@w : () } 0 .. 31; sub fifteens { my $hand = shift; $hand =~ s/[SCHD]//g; $hand =~ s/[JQK]/10/g; $hand =~ s/A/1/g; my @hand = split /,/, $hand; ( grep { sum(@hand[@$_]) == 15 } @combos ) * 2 }
The key is the @combos array. It contains a set of "combination keys", such as
for all the valid subsets of cards in a hand. It turns out there's only 26 of them. (It does not include any keys of length 1, since there's no way to get 15 from a single card.)[ 1,2 ], [ 1,2,3 ], [ 1,2,4 ], . . .
|
|---|