Perl算法:Permute和List :: AllUtils(uniq)

Ric*_*ard 4 perl

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)).是什么赋予了?

mob*_*mob 6

perldoc -f sort列出该sort函数的三种语法:

sort SUBNAME LIST
sort BLOCK LIST
sort LIST
Run Code Online (Sandbox Code Playgroud)

sort uniq @others匹配sort SUBNAME LISTsort 的语法.该公司预计uniq到是全局变量比较函数$a$b,并返回<0,0>0指示的相对顺序$a$b.

看起来你期待并想要sort LIST语法,这就是你说的时候得到的

sort(uniq(@others))
sort(uniq @others)
Run Code Online (Sandbox Code Playgroud)


ike*_*ami 5

算法::循环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)