Re: Is substr only way of getting nth character of string?
am 04.04.2008 21:25:15 von sheinrichOn Mar 21, 1:55 am, "Robbie Hatley"
> New version:
>
> #permute.perl
> use strict;
> use warnings;
> sub rand_int
> {
> my ($min, $max) = @_;
> return int ( $min + rand ( $max - $min + 0.999 ) ) ;}
>
> srand;
> my @Charset = map chr, 9, 32..126;
> my @TempCharset = @Charset;
> my @PermCharset;
> while (@TempCharset > 0)
> {
> my $RandomInt = rand_int(0, @TempCharset - 1);
> my $RandomChar = $TempCharset[$RandomInt];
> push @PermCharset, $RandomChar;
> splice @TempCharset, $RandomInt, 1;}
>
> print @PermCharset, "\n";
>
Better late than never.
This one is my favourite shuffling algo. It's called a 'fisher yates
shuffle' and perl allows to swivel elements in-place:
use strict;
use warnings;
my @array = 1..100;
for (my $i = @array; $i; ) {
my $j = int rand $i--;
next if $i == $j;
@array[$i,$j] = @array[$j,$i];
}
print "@array\n";
Give it a shot,
steffen