in reply to Randomize word

The process you describe is a shuffle. If you don't want to use List::Util which AFAIK is not core (for <5.8 ) then you could just use a Fisher Yates shuffle like this:

sub random { my @array = split //, shift; for (my $i = @array; --$i; ) { my $j = int rand ($i+1); @array[$i,$j] = @array[$j,$i]; } return join '', @array; } print random('hello');

UpdateAristotle notes that List::Util is core from 5.8.

cheers

tachyon

Replies are listed 'Best First'.
Re^2: Randomize word
by Roy Johnson (Monsignor) on Sep 07, 2004 at 14:34 UTC
    If you're going to roll your own shuffle, there's no reason you need to work on an array:
    sub rand2 { my $foo = shift; for (my $i = length($foo); --$i; ) { my $j = int rand ($i+1); (substr($foo, $i, 1), substr($foo, $j, 1)) = (substr($foo, $j, + 1), substr($foo, $i, 1)) } return $foo; }
    But then, there's no strong argument for shuffling in-place, either:
    sub rand3 { my $foo = shift; my $bar = ''; while (length $foo) { $bar .= substr($foo, rand(length $foo), 1, ''); } return $bar; }
    Benchmark results:
    Rate rand1 rand2 rand3 rand1 2928/s -- -27% -78% rand2 4008/s 37% -- -70% rand3 13282/s 354% 231% --
    Update: Benchmarked BrowserUK's shuffleword; it was about half as fast as rand3.

    Caution: Contents may have been coded under pressure.
Re^2: Randomize word
by Aristotle (Chancellor) on Sep 07, 2004 at 15:41 UTC

    List::Util is core as of 5.8.

    Makeshifts last the longest.