Brand Hilton <bhilton@adc.com> writes: > On Tue, Aug 03, 1999 at 05:18:18PM -0400, Chip Turner wrote: > > > > @cards = (0 .. 51); # or any number of them > > $passes = 1; # one pass should be sufficient for all but the most paranoid > > $cards[$_ % @cards] = $cards[rand(@cards) % @cards] foreach 0 .. ($passes * @cards - 1); > > Untested, I presume :-) Yours clobbers cards instead of swapping > them. That's what I get for not testing :) You are of course correct that it clobbers instead of shuffling. > This is similar, but actually works: > > @cards = (0 .. 51); # or any number of them > $passes = 1; # one pass should be sufficient for all but the most paranoid > foreach (0 .. ($passes * @cards - 1)) { > $rand = rand(@cards); > @cards[$rand % @cards, $_ % @cards] = @cards[$_ % @cards, $rand % @cards]; > } > > Unfortunately, it lacks the nifty foreach-as-a-statement-modifier. We can still use the infix foreach! Never understimate the desire for a Perl coder to use his or her favorite construct! @cards = (0 .. 51); # or any number of them $passes = 1; # one pass should be sufficient for all but the most paranoid $i = rand(@cards) % @cards, @cards[$i, $_ % @cards] = @cards[$_ % @cards, $i] foreach 0 .. ($passes * @cards - 1); Hmm. Still not perfect yet. @cards = (0 .. 51); # or any number of them $passes = 1; # one pass should be sufficient for all but the most paranoid @a = (rand(@cards) % @cards, $_ % @cards), @cards[@a] = @cards[reverse @a] foreach 0 .. ($passes * @cards - 1); That's maybe a bit better, but it's not pretty enough. Hmm. Too many variables, not enough perl internals. We can do better! @cards = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [ $_, rand(1 << 31) ] } (0 .. 51); That has a certain aesthetic niceness to it. I think someone did a similar one earlier. I'm not 100% convinced this is a truly random sort, but I think it should be pretty good. Hopefully the rand perl uses (which I hope desperately isn't the default rand that the OS comes with, but deep down I suspect it is) is decent enough to give a good distribution. > 'Course, if it was me, I'd just do > > use Algorithms::Numerical::Shuffle; > @cards = (0 .. 51); # or any number of them > @cards = shuffle(@cards) > > Not as much fun, maybe, but a lot quicker to type and a lot less > error-prone :-) Aww not much fun at all! :) Unless you count the intrinsic fun in using CPAN, which is pretty high. Okay that's enough fuy for now :) Chip -- Chip Turner chip@ZFx.com Programmer, ZFx, Inc. www.zfx.com PGP key available at wwwkeys.us.pgp.net ==== Want to unsubscribe from Fun With Perl? Well, if you insist... ==== Send email to <fwp-request@technofile.org> with message _body_ ==== unsubscribe