And if you want to do this more generically:
Define an unique order for each object. In this instance that happens to just be the card's value. Then create a list of hashes where a card is only added if one of the same order does not exist.
use List::Util qw(shuffle first);
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";
# Group Cards into Decks
my @deck;
for my $card (@pile) {
# Order of Object
my $ord = $card;
my $deck = first {! exists $_->{$ord}} @deck;
# Start new deck
if (! $deck) {
$deck = {};
push @deck, $deck;
}
$deck->{$ord} = $card;
}
# Results:
print "Decks:\n";
for my $deck (@deck) {
print "\t" . join(' ', values %$deck) . "\n";
}
When you view the results, you'll notice that each of the "decks" appear to be near identical. This is because of the internal implementation of hashes and the way that elements are assigned a place in the hash.
- 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.