Vengant - 3 years ago 269
Perl Question

# Generate all combinations of up to N digits, including repeating digits, in Perl

What's the best way to generate all combinations of 1 to N digits, where digits could be repeated in the combination? E.g, given array 0..2, the result should be:

0

1

2

00

01

02

10

11

12

20

21

22

000

001

002

010

011

etc.

I've played with Algorithm::Permute, but it looks likt it could generate just unique combinations of N numbers:

``````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;
}
}
``````

Thank you.

As its name suggests, `Algorithm::Permute` offers permutations. There are many mathematical variations on selecting k items from a population of N: with and without replacement, with and without repetition, ignoring order or not

It's hard to be certain, but you probably want `Algorithm::Combinatorics`

Here's some example code that reproduces at least the part of your expected data that you have shown. It's pretty much the same as zdim's solution but there may be something extra useful to you here

``````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
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download