use Modern::Perl;
use Algorithm::Permute;
use List::AllUtils qw/uniq/;
find_perms(1151);
sub find_perms {
my ($value) = @_;
my @others;
my @digits = split(//, $value);
my $perm = Algorithm::Permute->new( \@digits );
while (my @next = $perm->next()) {
my $number = join('', @next);
push @others, $number;
}
@others = sort uniq @others;
# this one works correctly
# @others = sort ( uniq( @others ));
say "FOUND @others";
}
Output:
FOUND 1115 1115 1115 1115 1115 1115 1151 1151 1151 1151 1151 1151 1511 1511 1511 1511 1511 1511 5111 5111 5111 5111 5111 5111
Run Code Online (Sandbox Code Playgroud)
嗨,
在发现Algorithm :: Permute正在产生重复之后,很可能是由于"1151"中的'1'我决定使用的数量uniq
.但是,在sort uniq
没有括号的情况下使用不会产生预期的结果.但是sort(uniq(@x))
.是什么赋予了?
perldoc -f sort
列出该sort
函数的三种语法:
sort SUBNAME LIST
sort BLOCK LIST
sort LIST
Run Code Online (Sandbox Code Playgroud)
sort uniq @others
匹配sort SUBNAME LIST
sort 的语法.该公司预计uniq
到是全局变量比较函数$a
和$b
,并返回<0
,0
或>0
指示的相对顺序$a
和$b
.
看起来你期待并想要sort LIST
语法,这就是你说的时候得到的
sort(uniq(@others))
sort(uniq @others)
Run Code Online (Sandbox Code Playgroud)
算法::循环的NextPermute
不产生重复,所以没有必要花费内存和CPU摆脱他们.
use Algorithm::Loops qw( NextPermute );
sub find_perms {
my @rv;
my @digits = sort split //, $_[0];
do {
push @rv, join '', @digits;
} while NextPermute(@digits);
return @rv;
}
say for find_perms(1151);
Run Code Online (Sandbox Code Playgroud)
1115
1151
1511
5111
Run Code Online (Sandbox Code Playgroud)