Perl
我决定有点反竞争,并展示您通常如何在 Perl 中编写此类问题。
最后还有一个 46(总)字符代码-golf 条目。
前三个示例都以此标题开头。
#! /usr/bin/env perl
use Modern::Perl;
# which is the same as these three lines:
# use 5.10.0;
# use strict;
# use warnings;
while( <> ){
chomp;
last unless $_;
Collatz( $_ );
}
-
简单的递归版本
use Sub::Call::Recur;
sub Collatz{
my( $n ) = @_;
$n += 0; # ensure that it is numeric
die 'invalid value' unless $n > 0;
die 'Integer values only' unless $n == int $n;
say $n;
given( $n ){
when( 1 ){}
when( $_ % 2 != 0 ){ # odd
recur( 3 * $n + 1 );
}
default{ # even
recur( $n / 2 );
}
}
}
-
简单的迭代版本
sub Collatz{
my( $n ) = @_;
$n += 0; # ensure that it is numeric
die 'invalid value' unless $n > 0;
die 'Integer values only' unless $n == int $n;
say $n;
while( $n > 1 ){
if( $n % 2 ){ # odd
$n = 3 * $n + 1;
} else { #even
$n = $n / 2;
}
say $n;
}
}
-
优化迭代版本
sub Collatz{
my( $n ) = @_;
$n += 0; # ensure that it is numeric
die 'invalid value' unless $n > 0;
die 'Integer values only' unless $n == int $n;
#
state @next;
$next[1] //= 0; # sets $next[1] to 0 if it is undefined
#
# fill out @next until we get to a value we've already worked on
until( defined $next[$n] ){
say $n;
#
if( $n % 2 ){ # odd
$next[$n] = 3 * $n + 1;
} else { # even
$next[$n] = $n / 2;
}
#
$n = $next[$n];
}
say $n;
# finish running until we get to 1
say $n while $n = $next[$n];
}
现在我将展示如何使用 v5.10.0 之前的 Perl 版本来完成最后一个示例
#! /usr/bin/env perl
use strict;
use warnings;
while( <> ){
chomp;
last unless $_;
Collatz( $_ );
}
{
my @next = (0,0); # essentially the same as a state variable
sub Collatz{
my( $n ) = @_;
$n += 0; # ensure that it is numeric
die 'invalid value' unless $n > 0;
# fill out @next until we get to a value we've already worked on
until( $n == 1 or defined $next[$n] ){
print $n, "\n";
if( $n % 2 ){ # odd
$next[$n] = 3 * $n + 1;
} else { # even
$next[$n] = $n / 2;
}
$n = $next[$n];
}
print $n, "\n";
# finish running until we get to 1
print $n, "\n" while $n = $next[$n];
}
}
基准测试
首先,IO 总是很慢的部分。因此,如果您真的按原样对它们进行基准测试,您应该从每个测试中获得大致相同的速度。
为了测试这些,我打开了/dev/null ($null) 的文件句柄,并编辑了每个say $n 以改为读取say {$null} $n。这是为了减少对IO的依赖。
#! /usr/bin/env perl
use Modern::Perl;
use autodie;
open our $null, '>', '/dev/null';
use Benchmark qw':all';
cmpthese( -10,
{
Recursive => sub{ Collatz_r( 31 ) },
Iterative => sub{ Collatz_i( 31 ) },
Optimized => sub{ Collatz_o( 31 ) },
});
sub Collatz_r{
...
say {$null} $n;
...
}
sub Collatz_i{
...
say {$null} $n;
...
}
sub Collatz_o{
...
say {$null} $n;
...
}
运行 10 次后,这是一个有代表性的示例输出:
速率递归迭代优化
递归 1715/s -- -27% -46%
迭代 2336/s 36% -- -27%
优化 3187/s 86% 36% --
最后,一个真正的代码高尔夫入口:
perl -nlE'say;say$_=$_%2?3*$_+1:$_/2while$_>1'
总共 46 个字符
如果您不需要打印起始值,您可以再删除 5 个字符。
perl -nE'say$_=$_%2?3*$_+1:$_/2while$_>1'
总共 41 个字符
实际代码部分有 31 个字符,但如果没有 -n 开关,代码将无法工作。所以我把整个例子都算进去了。