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

后端 未结 3 1155
故里飘歌
故里飘歌 2020-12-20 23:02

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,

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-20 23:13

    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)
    

提交回复
热议问题