in reply to Re: array shuffle
in thread array shuffle

I'm trying to test my skills without using the shuffle function. I was def using the wrong loop.

Here's my problem now though, I want to shuffle the "deck" twice.

using the  while (@deck) I can get the deck shuffled once, but when I use:

@hand = shuf(@deck); print "deck shuffled once:\n"; print"@hand\n"; @deck = @hand; @newhand = shuf(@deck); print"deck shuffled twice:\n"; print"@newhand\n";

I don't get the result I'm hoping for, what am I doing wrong now?

Replies are listed 'Best First'.
Re^3: array shuffle
by davido (Cardinal) on Aug 18, 2011 at 04:19 UTC

    Assuming that shuffling is simple is a mistake, and yet once you see an unbiased algorithm on paper (or screen) you will probably say, "Oooh, I get it." But done wrong, shuffling can introduce bias, and it's easy to do wrong.

    There is a nice article on Wikipedia: Fisher-Yates Shuffle. Implemented as a computer algorithm, it is sometimes known as the Knuth Shuffle. Also looking at the Pure Perl version of List::Util (here: Source for List::Util::PP) you will see a Perlish implementation of Fisher-Yates.

    Another post here pointed you to perlfaq4, which shows another Fisher-Yates implementation that is easier to read than the List::Util::PP version.

    For the masochistic or exceptionally curious: The Art of Computer Programming vol. 2 (3rd ed.), pg 145-146.


    Dave

Re^3: array shuffle
by jwkrahn (Abbot) on Aug 18, 2011 at 04:02 UTC
Re^3: array shuffle
by ikegami (Patriarch) on Aug 18, 2011 at 06:03 UTC
    You're using a global variable which you empty the first time around instead of passing the deck to your function. You need to properly scope your variables.