Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array sorting in Perl

Tags:

perl

I am new to Perl and stuck with a (likely simple) array sorting problem.

I've inherited some Perl code that reads lines from a text file into three 1-D arrays (x,y,z). I'd like to be able sort these arrays using one of the dimensions as the key and reordering the other two dimensions to match.

For example, if my input is:

  • @x = (1, 3, 2)
  • @y = (11,13,12)
  • @z = (21,23,22)

and I sort by x, I'd like the result to be:

  • @x = (1, 2, 3)
  • @y = (11,12,13)
  • @z = (21,22,23)

I could merge the three 1-D arrays into a 2-D array if that makes life easier.

like image 623
amb Avatar asked Jan 05 '11 15:01

amb


2 Answers

Merging all the arrays together isn't necessary. Use sort to get the correct index ordering for the elements in @x:

@sort_by_x = sort { $x[$a] <=> $x[$b] } 0 .. $#x;    #   ==> (0, 2, 1)

Then apply that index ordering to any other array:

@x = @x[@sort_by_x];
@y = @y[@sort_by_x];
@z = @z[@sort_by_x];
like image 137
mob Avatar answered Oct 08 '22 10:10

mob


use strict;
use warnings;
use Data::Dumper;

use List::Util qw(reduce);

my @x = (1, 3, 2);
my @y = (11, 13, 12);
my @z = (21, 23, 22);

my @combined = map { [ $x[$_], $y[$_], $z[$_] ] } 0 .. $#x;
my @sorted = sort { $a->[0] <=> $b->[0] } @combined;
my $split_ref = reduce { push @{$a->[$_]}, $b->[$_] for 0 .. $#$a; $a;} [[], [], []], @sorted;

print Dumper \@combined;
print Dumper \@sorted;
print Dumper $split_ref;

Which will essentially give you:

    [
      [
        1,
        2,
        3
      ],
      [
        11,
        12,
        13
      ],
      [
        21,
        22,
        23
      ]
    ];
like image 30
zakovyrya Avatar answered Oct 08 '22 09:10

zakovyrya