I'am new with perl and stucked with the following exercise. I have a multi-array and want order its element to descending to the inside arrays sum's. I want to make the order with Schwartzian transform.
This is my vector:
my @vectors = ( [1], [ 1, 2, 3 ], [4], [ 2, 2, 1 ] );
This is the expected vector:
@sorted_vectors = ( [1,2,3], [2,2,1], [4], [1] );
So far I am tried with these:
(1) #!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my @vectors = ( [1], [ 1, 2, 3 ], [4], [ 2, 2, 1 ] );
my @sorted_vectors;
# @sorted_vectors = ( [1,2,3], [2,2,1], [4], [1] );
my %hash=();
for(my $i=0;$i< scalar @vectors;$i++){
$hash{$i}=@vectors[$i];
}
for my $key ( sort { $hash{$b}[1] <=> $hash{$a}[1] } keys %hash ) {
push(@sorted_vectors,[@{$hash{$key}}]);
}
print Dumper( \@sorted_vectors );
(2)
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my @vectors = ( [1], [ 1, 2, 3 ], [4], [ 2, 2, 1 ] );
my @sorted_vectors;
# @sorted_vectors = ( [1,2,3], [2,2,1], [4], [1] );
my @sorted = map { $_->[0] }
sort { $a->[1] cmp $b->[1] }
map { [$_, foo($_)] }
@vectors;
sub foo{
my $res = 0;
foreach my $x (@_) {
$res+= $x;
}
return $res;
}
print Dumper(\@sorted);
cmpto<=>as you're comparing numbers. Thecmpwill only work as long as your totals are less than 10.