in reply to array shuffle

Don't modify an array over which you are iterating using foreach. You actually want while (@deck) here anyway. It will produce a really bad shuffle, though. To shuffle a list or array, one normally uses List::Util's shuffle.

Use use strict; use warnings;!!! You forgot to limit the scope many variables.

Replies are listed 'Best First'.
Re^2: array shuffle
by boom.roasted (Initiate) on Aug 18, 2011 at 03:54 UTC

    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?

      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

      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.