in reply to Re^2: keep track of array indexes
in thread keep track of array indexes

thanks.. interesting method. But the ultimate question is, if the order of @words is randomized, how would i re-order @order so that it still produces "this is a sentence" ? pseudo code:
@words = "this is my sentence" @order = 0, 3, 1, 2 print @order randomize(@words) @order = 2,1,0,3 randomize(@words) @order = 1,0,3,2
the code is somehow keeping track of changes in the @words array and updating the @order array.

Replies are listed 'Best First'.
Re^4: keep track of array indexes
by choroba (Cardinal) on Jan 02, 2016 at 20:58 UTC
    The answer is the same: Use a hash.
    #!/usr/bin/perl use warnings; use strict; use feature qw{ say }; use List::Util qw{ shuffle }; my @words = qw( this is my string ); my @order = 0 .. $#words; my %ord; @ord{@words} = 0 .. $#words; @words = shuffle(@words); @order = @ord{@words}; print do { local $" = "\t"; "@words\n", "@order\n" }; say join ' ', map $words[$_], sort { $order[$a] <=> $order[$b] } @order;
    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
      Nobody seemed to care, but words are not necessarily unique.

      So instead of hashing one index we need to store an array of indices per word.

      Cheers Rolf
      (addicted to the Perl Programming Language and ☆☆☆☆ :)
      Je suis Charlie!

        Only a slight modification needed.
        #!/usr/bin/perl use warnings; use strict; use feature qw{ say }; use List::Util qw{ shuffle }; my @words = qw( this is a string with a word ); my @order = 0 .. $#words; my %ord; push @{ $ord{ $words[$_] } }, $_ for 0 .. $#words; # <-- Here... @words = shuffle(@words); @order = @ord{@words}; print do { local $" = "\t"; "@words\n" }; say join "\t", map "[@$_]", @order; @order = map shift @$_, @order; # <-- and here. say join ' ', map $words[$_], sort { $order[$a] <=> $order[$b] } @order;
        ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
      Hello choroba. I have a question about your last line where you say @order. Not sure why it works out. Why does this work instead of saying 0..$#order? Maybe I'm missing something obvious.

      Update Wow, just took stepping away from the problem to see that both ways supply the same set of array indices. Knew it had to be obvious.