On 12/12/2006 04:00 AM, Rinku Mahesh wrote:
  Hi,
I've two arrays of same depth (let it be 6) 1st Array:- @unique {11 , 23, 44, 66, 900, 1009}
  2nd Array:- @occ_count {2, 77, 22, 2, 77,29}
Here I'm looking for a sorting mechanism with the following conditions:- a. Sort 2nd Array in descending order such that it should reflect {77,77,29,22,2,2} b. The values of 1st array should also change in accordance with the positions of elements of 2nd array such that sorting the 1st array should reflect {23,900,1009,44,11,66} 23 and 900 or 11 and 66 can be interchanged but whatever value is lesser should appear first in the list. c. As there are repeatations in 2nd Array (77 and 2) there could be two values associated with these elements in 1st array (23/900 or 11/66). Here 23 is lesser than 900 thus it should appear fist in the list. If the above explaination is confusing I'm looking for a way where every element of an array can be mapped to corresponding element of another array and as a whole both the arrays require a sorting w.r.t. 2nd array. Can anyone suggest an eficient way to implement same. TIA, Rinku



I hope this is both easy and efficient enough for you:

use strict;
use warnings;
use Sort::Key qw(nkeysort);
my (@unique, @occ_count);
@unique = (66 , 23, 44, 11, 900, 1009);
@occ_count = (2, 77, 22, 2, 77,29);

my @indexes = nkeysort { $occ_count[$_] * 10000 + $unique[$_] }
    (0..$#occ_count);
@unique = map $unique[$_], @indexes;
@occ_count = map $occ_count[$_], @indexes;
print "@unique\n";
print "@occ_count\n";



The line where @indexes is assigned is probably the most confusing, so I'll only explain that one. Sort::Key allows you to sort while specifying your key field in an easy and natural manner. Because I want to sort two arrays, I have to sort array indexes--not the arrays themselves; that's what (0..$#occ_count) does; it creates a list of array indexes.

Inside of the { ... }, I specify the key field on which to sort. The easy way to do this would be to use { $occ_count[$_] }, but that would only sort the array indexes based on what's in @occ_count, and I have to take @unique into consideration also, so I make the occ_count part of the forumula much more important than the "unique" part of the forumla by multiplying $occ_count[$_] by 10000; this should put it well above the range of numbers in @unique.

Then nkeysort tells Sort::Key to do a numeric sort.


HTH



--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to