【问题标题】:get all possible permutations of words in string using perl script使用 perl 脚本获取字符串中所有可能的单词排列
【发布时间】:2015-06-10 17:43:42
【问题描述】:

我有一个像这样的字符串,how are you,我想得到所有可能的单词 shuffle 像

how are you
are how you
you how are
you are how
are you how
how you are

如何在perl 脚本中实现它,我尝试了shuffle 函数,但它只返回一串随机播放。
如果你对Perl脚本不熟悉,你只能告诉我逻辑。

注意:字符串中的字数不固定。

【问题讨论】:

    标签: perl permutation word


    【解决方案1】:

    你说的是permutations。这可以通过 Algorithm::Permute 模块在 Perl 中完成:

    如果您已经安装了该模块,这里有一个 shell 单行代码可以为您完成:

    perl -e'
     use Algorithm::Permute qw();
     my $str = $ARGV[0]; 
     my @arr = split(/\s+/,$str);
     my $ap = new Algorithm::Permute(\@arr); 
     while (my @res = $ap->next()) { print("@res\n"); }
    ' 'how are you';
    ## you are how
    ## are you how
    ## are how you
    ## you how are
    ## how you are
    ## how are you
    

    【讨论】:

      【解决方案2】:

      您可以使用List::Permutor CPAN 模块:

      use strict;
      use warnings;
      
      use List::Permutor;
      
      my $perm = new List::Permutor qw/ how are you /;
      while (my @set = $perm->next)
      {
        print "@set\n";
      }
      

      输出:

      how are you
      how you are
      are how you
      are you how
      you how are
      you are how
      

      正如 bgoldst 建议的 Algorithm::Permute,为了更快地执行,您可以在不使用 while 循环的情况下编写此代码:

      use Algorithm::Permute;
      my @array = qw(how are you);
      Algorithm::Permute::permute {
          print "@array\n";
      }@array;
      

      【讨论】:

        猜你喜欢
        • 2017-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-18
        • 1970-01-01
        相关资源
        最近更新 更多