在Perl中生成最多N位数的所有组合,包括重复数字

问题描述 投票:0回答:2

生成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
2个回答
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);
}

output

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

-1
投票
my @digits = 0..2;
my $len = 3;
my @combinations = map glob("{@{[join ',', @digits]}}" x $_), 1..$len;
© www.soinside.com 2019 - 2024. All rights reserved.