http://www.perlmonks.org?node_id=219493


in reply to random number

Here's a snippit that will initialize an array and select a number while the array still has elements...what you do with the element is up to you...
use strict; my $max = 200; #number of elements for +array my @array = (0..$max-1); #initialize array while(@array !=0){ my $index = rand @array; #pick a random element o +f the existing array my $element = $array[$index]; #extract the element my @newarray = grep {$_ !=$element} @array; #remove the element @array = @newarray; #reset the array }
Addendum: See BrowserUk's reply for a more tidy/efficient method of extracting the element from the array

Replies are listed 'Best First'.
Re: Re: random number
by BrowserUk (Pope) on Dec 13, 2002 at 04:22 UTC

    Given that you know the index of the item you want to remove from the array, it would be much more efficient to use splice instead of grep to remove the item from the array.

    #replace my @newarray = grep {$_ !=$element} @array; #remove the element #with splice @array, $index, 1; #remove item from array; # and remove this. No need as the array has been modified. # @array = @newarray; #reset the array

    Examine what is said, not who speaks.

      #splice is still O(n) $array[$index] = $array[-1]; pop @array;

        True. And that's a neat solution.

        It would still be better to shuffle the array and simply pop the next one when you need it as was suggested at near the top of the thread.


        Examine what is said, not who speaks.

Re: Re: random number
by sauoq (Abbot) on Dec 13, 2002 at 23:40 UTC

    Shuffling the array as suggested by BrowserUk and traveler is the Right Way To Do It™ but if you insist on removing elements from the array, how about

    perl -le '@a=1..200; print while $_ = splice @a, rand @a, 1'
    ?

    -sauoq
    "My two cents aren't worth a dime.";
    
Re: Re: random number
by huskey (Beadle) on Dec 14, 2002 at 04:53 UTC
    thank you. it worked perfect.