Your algorithm does not accurately represent how one would achieve grouping of decks in real life. The easiest way to do that would almost certainly be to sort. First by suit, creating 4 individual piles. And the sorting each suit pile by rank. And finally separating the larger sorted pile of cards into individual decks.
The following script represents this algorithmically:
use List::Util qw(shuffle);
use strict;
# Ordered least to greatest
my @suit = qw(C D H S);
my @rank = ( 2 .. 10, qw(J Q K A) );
# Construct a standard deck
my @card = map {
my $suit = $_;
map { "$_$suit" } @rank
} @suit;
# Shuffle 4 piles of cards.
my @pile = shuffle( (@card) x 4 );
print "Pile\n\t@pile\n\n";
# Sort
my %ord_suit = map { $suit[$_] => $_ } ( 0 .. $#suit );
my %ord_rank = map { $rank[$_] => $_ } ( 0 .. $#rank );
my @pile_sorted = map { $_->[0] } sort {
$ord_suit{ $a->[1][1] } <=> $ord_suit{ $b->[1][1] }
|| $ord_rank{ $a->[1][0] } <=> $ord_rank{ $b->[1][0] }
} map { [ $_, [m/(.*)(.)/] ] } @pile;
# Group Cards into Decks
my @deck;
my $lastcard = '';
my $index;
for my $card (@pile_sorted) {
if ( $card ne $lastcard ) {
$index = 0;
}
else {
$index++;
}
push @{ $deck[$index] }, $card;
$lastcard = $card;
}
print "Decks\n";
foreach (@deck) {
print "\t@$_\n";
}
- Miller
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.