- 论坛徽章:
- 5
|
my $师傅, 我有一个问题,
一般我写这个问题代码是这样写的:
( 更少的代码更容易理解, 一点点优化代码在下一楼 )- sub SUM {
- my $sum;
- $sum += $_ for split //, shift;
- $sum;
- }
- while (<DATA>) {
- my ( $K, $N ) = split;
- my @mind = sort { $a->[1] <=> $b->[1] || $a->[0] cmp $b->[0] }
- map { [ $_, SUM($_) ] } 1 .. $N;
- my $index;
- for my $i ( 0 .. $#mind ) {
- if ( $mind[$i][0] == $K ) { $index = $i; last }
- }
- my $number = $mind[$K][0];
- say join "\t", $K, $N, $index, $number;
- }
- __DATA__
- 24 20000
- 31 100000
- 54 5000000
- 690 400000
复制代码 但你说:程序写得越简单, 越是高手
我尽我所能写我的代码如下: 我是非常满意的! {:2_168:}
我, 尽我所能的放弃了 perl 语言的特性, 让别人可以看懂我的 代码.- sub SUM {
- my ($number) = @_;
- my $len = length $number;
- my @chars;
- for ( my $i = 0 ; $i < $len ; $i++ ) {
- my $char = substr $number, $i, 1;
- push @chars, $char;
- }
- my $sum = 0;
- for my $c (@chars) {
- $sum = $sum + $c;
- }
- return $sum;
- }
- while ( my $line = <DATA> ) {
- chomp $line;
- my ( $K, $N ) = split /\t/, $line;
- my @wait_for_sort = ();
- for ( my $n = 1 ; $n <= $N ; $n++ ) {
- my $sum = SUM($n);
- my @two_elems = ();
- push @two_elems, $n;
- push @two_elems, $sum;
- push @wait_for_sort, [@two_elems];
- }
- my @Semi_products =
- sort { $a->[1] <=> $b->[1] || $a->[0] cmp $b->[0] } @wait_for_sort;
- my @array_in_mind = ();
- for my $semi (@Semi_products) {
- my @two_elems = @{$semi};
- my ( $number, $sum ) = @two_elems;
- push @array_in_mind, $number;
- }
- my $index;
- my $counter1 = 0;
- for my $num (@array_in_mind) {
- if ( $num == $K ) {
- $index = $counter1;
- }
- $counter1 = $counter1 + 1;
- }
- my $number;
- my $counter2 = 0;
- for my $num (@array_in_mind) {
- if ( $counter2 == $K ) {
- $number = $num;
- }
- $counter2 = $counter2 + 1;
- }
- say "$K\t$N\t$index\t$number";
- }
- __DATA__
- 24 20000
- 31 100000
复制代码 这行,我很好奇, 我们是否可以更简单写它 ? 让别人可以看懂 ?- my @Semi_products =
- sort { $a->[1] <=> $b->[1] || $a->[0] cmp $b->[0] } @wait_for_sort;
复制代码 可否给点思路 or 代码 呢?谢谢师傅!
回复 4# q1208c
|
|