in reply to Array problem

#! perl -slw use strict; use List::Util qw[ shuffle ]; my @start = qw[ dog cat bird mouse rat snake horse cow pig lizard lamb zebra lion elephant monkey ]; my @want = map{ join ' ', $start[ $_ ], ( shuffle @start[ 0 .. $_-1, $_+1 .. $#start ] )[ 0 .. 2 ] } 0 .. $#start; print for @want; __END__ dog cat lamb lizard cat lamb mouse pig bird pig monkey lizard mouse bird pig snake rat dog bird lion snake mouse horse rat horse lion elephant lamb cow lamb horse bird pig cat rat bird lizard bird horse cat lamb rat zebra dog zebra monkey horse snake lion pig zebra dog elephant lamb monkey cow monkey rat lamb snake

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
"Too many [] have been sedated by an oppressive environment of political correctness and risk aversion."

Replies are listed 'Best First'.
Re^2: Array problem
by ikegami (Patriarch) on Sep 27, 2008 at 08:06 UTC

    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!

      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.
Re^2: Array problem
by AnomalousMonk (Archbishop) on Sep 27, 2008 at 07:30 UTC
    Nice, very nice! And a lot better than my effort, which I won't bother to post having seen BrowserUK's; and more than being nice code, it has the additional quality that the the OPer will, I think, hesitate to turn it in for his homework assignment without doing a lot of digging to figure out just what is going on inside this little gem.