Fabrice Baro said:
I want to randomly select a certain number of letters among my
string.
I'm planning to shuffle an index and pick the desired number of
letters.
Original:
0 1 2 3 4 5 <- index
L G R D T I <- letters
Shuffle:
4 2 5 1 0 3
T R I G
^
Pick until here
Does anyone see a better way ?
Fabrice Baro said:
I want to randomly select a certain number of letters among my
string.
I'm planning to shuffle an index and pick the desired number of
letters.
Original:
0 1 2 3 4 5 <- index
L G R D T I <- letters
Shuffle:
4 2 5 1 0 3
T R I G
^
Pick until here
What is the condition that determines where 'here' is? Is it the same each
time or is it different based on some condition? (i.e. until a specific
letter is found? Or x number of letters?)
Why build an array, and an array of the indexes when you can just shuffle
the array and then step through the indexes until you meet the above
condition? Is there some reason the array of letters needs to preserve it's
order (which can't be met by preserving the pre-split sting?)?
Shuffling an array is a FAQ.... So maybe your answers to the two above
questions will help you a little...
Modified from PerlFAQ4
my $string = 'abcdefghijklmnopqrstuvwxyz';
my @letters = split //, $string;
fisher_yates_shuffle( \@letters ); # randomize @letters in place
print @letters;
sub fisher_yates_shuffle {
my $deck = shift; # $deck is a reference to the array
my $i = @$deck;
while ($i--) {
my $j = int rand ($i+1);
@$deck[$i,$j] = @$deck[$j,$i];
}
}
In this array the indexes remain sequential and any letter can be accessed
directly by $letters[$arrayindex]...
I hope I'm not completely on the wrong track...
P
--