【问题标题】:Generate all combinations of up to N digits, including repeating digits, in Perl在 Perl 中生成最多 N 个数字的所有组合,包括重复数字
【发布时间】:2017-12-22 11:24:04
【问题描述】:

生成 1 到 N 位数字的所有组合的最佳方法是什么,其中数字可以在组合中重复?例如,给定数组 0..2,结果应该是:

0
1
2
00
01
02
10
11
12
20
21
22
000
001
002
010
011
等等

我玩过 Algorithm::Permute,但看起来它可以生成 N 个数字的唯一组合:

for( my $a = 0; $a < 3; $a++ ) {
        for( my $b = 0; $b < 3; $b++ ) {
                my @array = $a..$b;
                Algorithm::Permute::permute {
                        my $Num = join("", @array);
                        print $Num;
                        sleep 1;
                } @array;
        }
}

谢谢。

【问题讨论】:

    标签: perl combinations


    【解决方案1】:

    顾名思义, Algorithm::Permute 提供排列。从 N 群体中选择 k 个项目有许多数学变化:有和没有替换,有和不重复,不分先后

    很难确定,但您可能想要 Algorithm::Combinatorics

    这里有一些示例代码,它至少可以重现您所显示的预期数据的一部分。它与 zdim 的 解决方案几乎相同,但这里可能对您有一些额外的用处

    use strict;
    use warnings 'all';
    use feature 'say';
    
    use Algorithm::Combinatorics 'variations_with_repetition';
    
    my @data = 0 .. 2;
    
    for my $k ( 1 .. @data ) {
        say @$_ for variations_with_repetition(\@data, $k);
    }
    

    输出

    0
    1
    2
    00
    01
    02
    10
    11
    12
    20
    21
    22
    000
    001
    002
    010
    011
    012
    020
    021
    022
    100
    101
    102
    110
    111
    112
    120
    121
    122
    200
    201
    202
    210
    211
    212
    220
    221
    222
    

    【讨论】:

      【解决方案2】:
      my @digits = 0..2;
      my $len = 3;
      my @combinations = map glob("{@{[join ',', @digits]}}" x $_), 1..$len;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-10
        相关资源
        最近更新 更多