Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: random elements from array - new twist

by Theseus (Pilgrim)
on Nov 05, 2002 at 14:21 UTC ( [id://210463]=note: print w/replies, xml ) Need Help??


in reply to random elements from array - new twist

Call me crazy, but wouldn't this be a much more simple solution? This results in your 5 random elements from the array being the 5 elements in %hash;
my %hash; my @array = ('one','two','three','four','five','six','seven','eight',' +nine','ten','eleven','twelve','thirteen','fourteen','fifteen'); while ((scalar keys %hash) < 5) { my $r = $array[rand(@array)]; $hash{$r} = $r; }

Replies are listed 'Best First'.
Re: Re: random elements from array - new twist
by Popcorn Dave (Abbot) on Nov 05, 2002 at 16:38 UTC
    ++ for that! The only problem I can see is if the original array has duplicate information, then that won't work. If however the original array is made up of unique items, then you'd be fine I would think.

    There is no emoticon for what I'm feeling now.

      The original poster said he wanted to make sure there were no duplicates returned out of the array, that's what makes the hash perfect for this particular problem. IMHO, anyway...
        It isn't very efficient, though, is it? Every time the loop runs, it has to pick a random number and check/assign the hash key. It could pick the same element several times since the array doesn't change. Also, if for any reason that array was less than five unique elements long you would get an endless loop. SpaceAce

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://210463]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (3)
As of 2024-04-23 23:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found