CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Randomising Arrays

 



andy7t
User

Sep 20, 2003, 11:34 AM

Post #1 of 5 (563 views)
Randomising Arrays Can't Post

Hello, how do i randomise the contents of an array.

At the moment they are in alphabetical order, so i want to just be able to randomise the array.

I thought something like

rand(@array);

or something.


KevinR
Veteran


Sep 20, 2003, 5:01 PM

Post #2 of 5 (559 views)
Re: [andy7t] Randomising Arrays [In reply to] Can't Post

I don't know if there is a module already made for doing something like you want, but this will also work, its crude but effective :)


Code
#!/perl/bin/perl.exe 
print qq~Content-type: text/html\n\n~;
use strict;

my @array = qw(Joe Fred Kevin John Paul Andy Mike Harry);
my @new;

@array = &randomize(@array);

sub randomize {
my $r_num = int(rand(int(@array)));
push @new, $array[$r_num];
delete $array[$r_num];
&randomize if @array;
return (@new);
}

print "@array";

-------------------------------------------------


Owen
Novice

Sep 20, 2003, 6:23 PM

Post #3 of 5 (554 views)
Re: [andy7t] Randomising Arrays [In reply to] Can't Post

This seems to be one of those occasions when Perl can read your mind! No complaints. She just knows that you need an integer. I like this language because its interpreter has common sense.


Code
 my @ary = qw(a b c d e f); 
print $ary[rand @ary], "\n";



Owen.


KevinR
Veteran


Sep 20, 2003, 11:46 PM

Post #4 of 5 (551 views)
Re: [Owen] Randomising Arrays [In reply to] Can't Post

what type of results are you expecting from the code you posted Owen? That will return a single random element of the array as far as I can tell just by looking at it.
-------------------------------------------------


davorg
Thaumaturge / Moderator

Sep 21, 2003, 1:23 AM

Post #5 of 5 (548 views)
Re: [andy7t] Randomising Arrays [In reply to] Can't Post

This is a FAQ.

How do I shuffle an array randomly?

--
Dave Cross, Perl Hacker, Trainer and Writer
http://www.dave.org.uk/
Get more help at Perl Monks

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives