in reply to random index in array - no duplicates

You're looking for a shuffle. Once the array is shuffled, you can pull them sequentially. If you don't care if the elements get out of order, use an in-place shuffle. If the order of the elements is important, create a second array of indexes and shuffle that.

my $array = shift; my $i; for ($i = @$array; --$i; ) { my $j = int rand ($i+1); @$array[$i,$j] = @$array[$j,$i]; }

This is the Fisher-Yates algorithm, shuffles the array in place - very efficient, and lifted straight from perldoc -q shuffle

Replies are listed 'Best First'.
Re: Re: random index in array - no duplicates
by samtregar (Abbot) on Jun 07, 2002 at 01:03 UTC
    Or simpler still:

    use List::Util 'shuffle'; @array = shuffle @array;

    -sam

Re: Re: random index in array - no duplicates
by jryan (Vicar) on Jun 08, 2002 at 00:35 UTC
    One problem with this, however, is that if the array contains multiple elements with the same value, they will still show up multiple times. Best to filter them out first.
      The OP wrote "but what if I want to be sure that I don't get a duplicate index?"

      I'm pretty sure he was worrying about pulling the same element twice from the array, not worrying about duplicate elements. If there are duplicate elements, yes he would want to weed them out first.