http://qs1969.pair.com?node_id=139915


in reply to Random but non-repeating array loop

As japhy suggests, the Fisher-Yates shuffle is a good solution. If you want to save yourself the trouble of coding it, I've got it implemented in Math::NumberCruncher. Math::NumberCruncher also has numerous other similar functions that may be useful. Using Math::NumberCruncher, you could do the above like so:
use strict; use Math::NumberCruncher; my @chars = ( 'A' .. 'Z' ); my $ref = Math::NumberCruncher->new(); $ref->ShuffleArray( \@chars ); foreach my $char ( @chars ) { print $char, "\n"; }

UPDATE: Pursuant to Juerd's post, in the interest of TMTOWTDI, here's the code using Math::NumberCruncher through its original functional interface:
use strict; use Math::NumberCruncher; my @chars = ( 'A' .. 'Z' ); Math::NumberCruncher::ShuffleArray( \@chars ); foreach my $char ( @chars ) { print $char, "\n"; }


___________________
Kurt

Replies are listed 'Best First'.
Re: Re: Random but non-repeating array loop
by Juerd (Abbot) on Jan 18, 2002 at 23:48 UTC
    Nice module, but why can it do OO? It seems to me that there's no persistent data, so an object isn't useful. Am I wrong here?

    2;0 juerd@ouranos:~$ perl -e'undef christmas' Segmentation fault 2;139 juerd@ouranos:~$

      Thanks. And you're absolutely right...there isn't a need for it to do OO. You don't have to use it that way; it still supports use as functions. In the first versions, it didn't have an OO interface, but I added it as an option for the sake of being complete, and also to open the door for the use of persistent data in future versions. It is also handy as shorthand if you're making repeated calls to numerous functions within Math::NumberCruncher.
      ___________________
      Kurt