×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
• Talk With Other Members
• Be Notified Of Responses
• Keyword Search
Favorite Forums
• Automated Signatures
• Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

#### Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

# Perl FAQ

## Little tricks

Get 'x' number of unique, random, elements from an array by KevinADC
Posted: 3 Feb 07 (Edited 15 Feb 07)

----------------------------
ignore this section:
shuffle

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

Two ways (of many more I am sure) of returning "x" number of random yet unique elements from one array to a new list/array. First way uses the core module List::Util.

#### CODE

use List::Util qw/shuffle/;
my @pop = (1..100);
my $samples = 30; my @sample = (shuffle(@pop))[0..$samples-1];
print "@sample";

The shuffle() function randomly shuffles (mixes) the array. Then using an array slice [0..x] we take just the number of elements we want from the beginning of the shuffled array.

The second way uses a hash to insure uniqueness and the rand() function to get random elements from the array.

#### CODE

my @pop = (1..100);
my $samples = 30;# see note below my @sample = rand_sample(30,@pop); print "@sample"; sub rand_sample { my ($n,@n) = (shift,@_);
return 0 unless ($n < scalar @n);# see note below my %seen = (); until (keys %seen ==$samples) {
$seen{$pop[rand @pop]}=1;
}
return(keys %seen);
}

The "until" loop continues until we have the requested number of samples from the original array. Because hash keys must be unique, we get a list of unrepeated samples from the original array.

Note: this value must be less than the length of the array or the script will go into an infinte loop. It could be equal but then all you would be doing is shuffling the original array.

Back to Perl FAQ Index
Back to Perl Forum

Close Box

# Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

• Talk To Other Members
• Notification Of Responses To Questions
• Favorite Forums One Click Access
• Keyword Search Of All Posts, And More...

Register now while it's still free!