2

I wand to sort a 3-dimension array in Perl. The elements of the array are in the form:

$arr_3d[indA][indB][indC] , and each element for indC=1 is a number

What I need is, for a given value of indA, sort all the sub-arrays indexed/defined by indB, with the decreasing order of the value of $arr_3d[indA][indB][indC=1],.

e.g. for an 1x2x2 array if:

$arr_3d[1][1][1] = 1
$arr_3d[1][1][2] = 4
$arr_3d[1][2][1] = 2
$arr_3d[1][2][2] = 3

Then after sorting :

$arr_3d[1][1][1] = 2
$arr_3d[1][1][2] = 3
$arr_3d[1][2][1] = 1
$arr_3d[1][2][2] = 4

So after sorting the sub-arrays $arr_3d[1][1] and $arr_3d[1][2] are swapped. Sorry for the messed up description.. Any ideas?

Regards, Giorgos

ikegami
  • 367,544
  • 15
  • 269
  • 518
yorgo
  • 477
  • 1
  • 6
  • 14
  • 4
    That's not a 1x2x2, that's a 2x3x3. Do you really put nothing in index zero? That's going to cause you all kinds of headaches. – ikegami Sep 04 '13 at 20:23

1 Answers1

1

This is related to the " Schwartzian transform in Perl? " . You are really just sorting a single array (@{ $arr_3d[$indA] }).

I test this and it works. You are probably using Fortran index notation (starting at 1), so I changed it to C indexing (starting at 0).

use Data::Dumper;

my @arr_3d ; 
$arr_3d[0][0][0] = 1; 
$arr_3d[0][1][0] = 2; 
$arr_3d[0][0][1] = 4; 
$arr_3d[0][1][1] = 3; 
my $indA = 0; 
my $indC = 0;

my @temp = @{ $arr_3d[$indA] };

@{ $arr_3d[$indA] } = sort { $b->[$indC] <=> $a->[$indC] } @temp;


print Dumper(\@arr_3d);
Community
  • 1
  • 1
Mark Lakata
  • 19,989
  • 5
  • 106
  • 123
  • Thanks,I run the following code but gives with a "Modification of a read-only value attempted" error at the last lines: my @arr_3d ; $arr_3d[1][1][1] = 1; $arr_3d[1][2][1] = 2; $arr_3d[1][1][2] = 4; $arr_3d[1][2][2] = 3; my $indA = 1; my $indC = 1; @{ $arr_3d[$indA] } = sort { $b->[$indC] <=> $a->[$indC] } @{ $arr_3d[$indA] }; – yorgo Sep 04 '13 at 20:38
  • Try again. I fixed the example. – Mark Lakata Sep 05 '13 at 00:44
  • I have not down-voted. I tried to up-vote but my "reputation" credit was not enough as I am a new user. – yorgo Sep 05 '13 at 20:33
  • @user2405602 - Someone down voted, not sure who. Sorry, I didn't mean to blame you. – Mark Lakata Sep 06 '13 at 00:04