Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1325
  • Last Modified:

how to shuffle an array in perl

Hi experts. I am trying to make a program with perl to shuffle an array. It is basically a card game. I am using pop, shift and push functions in order to do this but not too sure how. Help would be greatly appreciated thanks.
0
micromarch
Asked:
micromarch
  • 2
  • 2
1 Solution
 
ozoCommented:
perldoc -q shuffle
Found in pods/perlfaq4.pod
       How do I shuffle an array randomly?

       If you either have Perl 5.8.0 or later installed, or if you have
       Scalar-List-Utils 1.03 or later installed, you can say:

           use List::Util 'shuffle';

               @shuffled = shuffle(@list);

       If not, you can use a Fisher-Yates shuffle.

           sub fisher_yates_shuffle {
               my $deck = shift;  # $deck is a reference to an array
               my $i = @$deck;
               while ($i--) {
                   my $j = int rand ($i+1);
                   @$deck[$i,$j] = @$deck[$j,$i];
               }
           }

           # shuffle my mpeg collection
           #
           my @mpeg = <audio/*/*.mp3>;
           fisher_yates_shuffle( \@mpeg );    # randomize @mpeg in place
           print @mpeg;

       Note that the above implementation shuffles an array in place, unlike
       the List::Util::shuffle() which takes a list and returns a new shuffled
       list.

       You've probably seen shuffling algorithms that work using splice, ran-
       domly picking another element to swap the current element with

           srand;
           @new = ();
           @old = 1 .. 10;  # just a demo
           while (@old) {
               push(@new, splice(@old, rand @old, 1));
           }

       This is bad because splice is already O(N), and since you do it N
       times, you just invented a quadratic algorithm; that is, O(N**2).  This
       does not scale, although Perl is so efficient that you probably won't
       notice this until you have rather largish arrays.
0
 
micromarchAuthor Commented:
yeh that works but my co-workers want me to use push,shift and pop.
0
 
ozoCommented:
why would they want you to do that?
would your co-workers allow you to use an auxilliary array?
you could implement the slice using push and shift
0
 
micromarchAuthor Commented:
what do they mean by returning an element for example the pop function? i can return the element i removed somewheres else?
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now