in reply to Re: Array problem
in thread Array problem

A slight alternative is to shuffle the indexes.

my @want = map{ "@start[ $_, ( shuffle 0 .. $_-1, $_+1 .. $#start )[ 0 .. 2 ] ]" } 0 .. $#start;

Don't even need join anymore!

Replies are listed 'Best First'.
Re^3: Array problem
by JavaFan (Canon) on Sep 27, 2008 at 09:54 UTC
    But neither are a good solution if the array is large: for each element, you're shuffling (almost) the entire array, just to get three elements. It makes for a quadratic solution, where a linear will do.
        Just don't shuffle the entire array; stop if you have shuffled three elements (taking care you don't shuffle in the leading animal).
        my @animals = qw [dog cat bird mouse rat snake horse cow pig lizard lamb zebra lion elephant monkey]; my @scratch = @animals; foreach my $animal (@animals) { for (my $j = @scratch - 1; $j >= @scratch - 3; $j --) { my $r = rand ($j + 1); @scratch[$j, $r] = @scratch[$r, $j]; if ($scratch[$j] eq $animal) { my $r = rand ($j); @scratch[$j, $r] = @scratch[$r, $j]; } } say "$animal @scratch[-3..-1]"; }
        As one can see easily, the running time inside the main loop is independent of the size of the array, hence, O(1), making the entire program run in linear time.