Dear all,
I have several arrays within which the order of the elements are important. I found this easier to code than a multi-tier hash. However, when I sort one array, I would like to change the order of the other arrays likewise.
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:
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);
}
}
}
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.
Many thanks
Sam
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.