Arunesh Singh
Arunesh Singh

Reputation: 3535

How to Sort 2D array Perl?

May be I am missing something. First It seemed too easy to me.I thought I can easily achieve it using map{}sort{}map{} ,but now it became complicated to me.

So, finally the problem is I have an array:

@array=(['b','e','d'],['s','a','f'],['g','i','h']);

and I want sorted array like

@sorted_array=(['a','f','s'],['b','d','e'],['g','h','i']);

I wrote

##sort based on columns########
my @sorted_array= map{my @sorted=sort{$a cmp $b}@$_;[@sorted]}@array;

###sort on rows####
my @sorted_array= map{$_->[0]}sort{$a->[1] cmp $b->[1]} map{[$_,"@$_"]}@array;

But I was not sure how to wrap it into one(for both rows and column). Can I achieve this using Schwartzian transform.

Upvotes: 0

Views: 407

Answers (2)

LeoNerd
LeoNerd

Reputation: 8532

This is two separate sorts. First you want to sort the inner arrays individually, then you can sort the outer array by, perhaps, the first element of each of the inner ones.

use List::UtilsBy qw( sort_by );

my @array =( [qw(b e d)], [qw(s a f)], [qw(g i h)] );

# sort the inner ones individually
@$_ = sort @$_ for @array;

# sort the whole by the first element of each
my @sorted_array = sort_by { $_->[0] } @array;

Or if you'd prefer doing it all in one go and avoiding the temporary mutation:

my @sorted_array = sort_by { $_->[0] }
                   map { [ sort @$_ ] } @array;

Upvotes: 0

mpapec
mpapec

Reputation: 50647

Yes, you can use it,

use strict;
use warnings;

my @array =( [qw(b e d)], [qw(s a f)], [qw(g i h)] );

my @sorted_array = 
map { $_->[0] }
sort {
  $a->[1] cmp $b->[1]
}
map {
  my $r = [ sort @$_ ];
  [$r, "@$r"];
}
@array;

use Data::Dumper;
print Dumper \@sorted_array;

output

$VAR1 = [
      [
        'a',
        'f',
        's'
      ],
      [
        'b',
        'd',
        'e'
      ],
      [
        'g',
        'h',
        'i'
      ]
    ];

Upvotes: 3

Related Questions