Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating all possible permutations for a given base and number of digits

I'm sure this is pretty simple, but I'm stumped for a way to do this. Essentially if I have an array with P collumns and V^P rows, how can I fill in all the combinations, that is, essentially, all possible numbers in base V of P digits. For example, for P=3 and V=2:

000
001
010
011
100
101
110
111

Keep in mind that this is an 2 dimensional array, not an array of ints.

For P=4 and V=3.

0000
0001
0002
0010
0011
0012
....

Having this array generated, the rest of work for what I'm trying to devolop is trivial. So having some code/tips on how to do this would be greatly appreciated. Thanks.

like image 792
andrepd Avatar asked Apr 23 '12 08:04

andrepd


1 Answers

Taking your example with P=3 and V=2, in the first column you need this sequence of numbers:

0, 0, 0, 0, 1, 1, 1, 1

So you essentially want four 0's followed by four 1's.

In the second column you need:

0, 0, 1, 1, 0, 0, 1, 1

So you want two 0's followed by two 1's, followed by the same again.

In general, in column number n, you need V^(P-n) of each digit, repeated V^(n-1) times.

Example when P=3 and V=2:

Column 1: We need V^(P-n) = 2^(3-1) = 4 of each digit, repeated V^(n-1) = 2^0 = 1 times:

[0, 0, 0, 0, 1, 1, 1, 1]

Column 2: We need V^(P-n) = 2^(3-2) = 2 of each digit, repeated V^(n-1) = 2^1 = 2 times:

[0, 0, 1, 1], [0, 0, 1, 1]

Column 3: We need V^(P-n) = 2^(3-3) = 1 of each digit, repeated V^(n-1) = 2^2 = 4 times:

[0, 1], [0, 1], [0, 1], [0, 1]

Some Python code that generates this sequence:

def sequence(v, p, column):
    subsequence = []
    for i in range(v):
        subsequence += [i] * v**(p - column)
    return subsequence * v**(column - 1)
like image 155
Eliot Ball Avatar answered Oct 16 '22 05:10

Eliot Ball