The algorithm from Arithmetic::Numerical::Shuffle is actually the Fischer-Yates shuffle (at least it was last time I checked). For easy reference perlfaq4 answers this question with that same algorithm. Just copy and paste if you want.
The alternate version below was authored by Abigail. It does an inplace shuffle and can take a list as an argument (instead of just an array reference).
sub shuffle {
for (my $i = @_; $i;) {
my $j = rand $i --;
@_ [$i => $j] = @_ [$j => $i]
}
@_;
}
As to your code, two main problems. First of all int(rand($x)) is what you want. Otherwise you get fractional numbers and so appear unique in your %seen hash, but don’t to array subscripts which use them as ints. Next is $DECK[$i] = $1;, what I think you meant is $DECK[$_] = $i. The variable $1 is for regex matching... did you perhaps mean $_?
Either way I’d suggest using the Fisher-Yates shuffle instead, once you’ve ponder it’s workings. It’s a much more efficient method. |