seaver has asked for the wisdom of the Perl Monks concerning the following question:
I can create a hash that stores the former index of an element, but the elements in any of the arrays are non-unique. It seems to me that I'll have to do this:
The above code should give me an array which indicates, for every index, the previous index. I am sure however that there is an easier solution that I've missed, perhaps involved map, of which i've no experience.my @array=('C','B','A','C'); my %hash=(); for(my $i=0;$i<scalar(@array);$i++){ $hash{$i}=$array[$i]; } @array=sort @array; my %found=(); my @sorted_indexes=(); foreach my $k(sort {$a <=> $b } keys %hash){ for(my $i=0;$i<scalar(@array);$i++){ if($array[$i] eq $hash{$k} && !exists($found{$hash{$k}}){ print $hash{$k}."-> Former: ".$k." Latter: ".$i."\n"; $found{$hash{$k}}=1; push(@sorted_indexes,$i); } } }
Many thanks
Sam
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Remembering original order of an array
by ikegami (Patriarch) on Sep 04, 2007 at 19:20 UTC | |
|
Re: Remembering original order of an array
by menolly (Hermit) on Sep 04, 2007 at 20:33 UTC | |
|
Re: Remembering original order of an array
by CountZero (Bishop) on Sep 04, 2007 at 19:21 UTC | |
|
Re: Remembering original order of an array
by Jenda (Abbot) on Sep 05, 2007 at 07:20 UTC | |
|
Re: Remembering original order of an array
by seaver (Pilgrim) on Sep 04, 2007 at 19:17 UTC | |
by ikegami (Patriarch) on Sep 04, 2007 at 19:27 UTC |