in reply to random index in array - no duplicates

As a bit of a golf Challenge:
$r=(grep!$$_++,@a)[rand@a] #evil

That probably doesn't help you so much though, does it? Lets work through the first one, and re-write it a bit clearer as we go along.

# create a counter to store the number of times the variable has # been encountered. my %counts; while (1) { my %h = %counts; # Allow only the elements that haven't been seen yet. Check the # perlfaq for more details my @unique = grep {!$h{$_}++} @array; # if @unique has no elements, there aren't any non-duplicates left last unless (@unique); # grab a random index my $random_index = int(rand(@unique)); # get a random element my $random_element = $unique[$random_index]; print "Random non duplicate element is: ", $random_element, "\n"; # add the element to the counter so that it doesn't get set $counts{$random_element}++; }

Thats a bit less efficient than the first example, but much more readable. If you have any questions about it, just respond.

Replies are listed 'Best First'.
Re: Re: random index in array - no duplicates
by emilford (Friar) on Jun 07, 2002 at 17:50 UTC
    Thanks for the suggestion. I tried incorporating your code exactly as it is into my program, but I was still getting duplicate values. It was probably a mistake on my part. Either way, I followed your logic and was able to implement my own version that is working great! Thanks!