On approximately 8/26/2004 1:42 AM, came the following characters from the keyboard of $Bill Luebkert:

Charles K. Clarkson wrote:


   There are two problems with the hash solutions.
One, the original order is lost. And two, they assume
at least one array contains only unique values.


You're correct on two (if indeed the values aren't unique), but
since the array wasn't modified and is still intact, you're
wrong on one since the hash can be sorted rather than the array.

He's correct on one also... the _original_ order _is_ lost. On the other hand, nothing stated about the problem implied that knowing the original order is or is not a requirement of the solution.


If the OP was "minimizing" the problem down to 2 arrays, but really has more arrays, Charles's solution of sorting the indices scales up much better. The hash solution only works if the scenario is limited to two parallel arrays (and one contains guaranteed unique values).

Another solution that would scale better to multiple arrays, or could be used anyway, was hinted at by Mike Trotman.... the question of if parallel arrays in the best data structure for the problem.

Instead of having separate parallel arrays, perhaps the data for the problem at hand could be expressed as an array of arrays... Not sure where the data is coming from initially, but instead of making parallel arrays of single elements, one could perhaps originate the data into a form like:

@arall = ( [ "sort", 1 ], [ "me", 2 ], [ "now", 3 ] );

Then the sorting can be done with

@arall = sort { $a->[0] cmp $b->[0]) @arall;

This would easily scale to additional parallel data items, has no dependency on uniqueness, and also destroys the original order... but if preserving the original order matters, one could sort indices (similar to the quotes below, or one could "copy" the data while sorting, via

@arsort = ( [ "sort", 1 ], [ "me", 2 ], [ "now", 3 ] );


   We could sort both arrays by sorting the indices
of one array.

my @first_names = qw( fred  john   sam   john );
my @last_names  = qw( white rubble smith smith );

my @indices_by_last  =
   sort {  $last_names[$a] cmp  $last_names[$b] }
        0 .. $#last_names;

my @indices_by_first =
   sort { $first_names[$a] cmp $first_names[$b] }
        0 .. $#last_names;


print "$_\n" foreach @first_names[ @indices_by_last ]; print "\n"; print "$_\n" foreach @last_names[ @indices_by_last ];

print "\n\n";

print "$_\n" foreach @first_names[ @indices_by_first ];
print "\n";
print "$_\n" foreach  @last_names[ @indices_by_first ];

__END__




-- Glenn -- http://nevcal.com/ =========================== The best part about procrastination is that you are never bored, because you have all kinds of things that you should be doing. _______________________________________________ Perl-Win32-Users mailing list [EMAIL PROTECTED] To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to