in reply to Re: 52 Perl Pickup
in thread 52 Perl Pickup

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