【发布时间】:2015-01-17 23:11:48
【问题描述】:
我是 perl 新手,坚持以下练习。 我有一个多数组,并希望将其元素降序到内部数组总和。 我想用 Schwartzian 变换来排序。
这是我的矢量:
my @vectors = ( [1], [ 1, 2, 3 ], [4], [ 2, 2, 1 ] );
这是预期的向量:
@sorted_vectors = ( [1,2,3], [2,2,1], [4], [1] );
到目前为止,我已经尝试过这些:
(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);
【问题讨论】:
-
在比较数字时,您需要将
cmp更改为<=>。cmp仅在您的总数小于 10 时才有效。