简体   繁体   English

生成组合行

[英]Generating rows of combinations

I don't know how I should formulate this question but I hope I can explain what I want to achive.我不知道我应该如何提出这个问题,但我希望我能解释我想要达到的目标。

So I got a set of characters [A, B, C].所以我得到了一组字符[A,B,C]。

I want to generate the minimal amount of rows with length of N needed to contain all possible combinations of [A, B, C].我想生成包含[A,B,C]的所有可能组合所需的长度为N的最少行。

Example: when N = 4, it generates something like this with 9 rows of length N(1 column = 1 row)示例:当 N = 4 时,它会生成 9 行长度为 N(1 列 = 1 行)的类似内容

AAABBBCCC
ABCCABBCA
BACACBCBA
ABCABCABC

For example the first row [A, A, B, A] contains the following combinations(1 column = 1 combination), notice how the combinations can wrap around the row.例如,第一行 [A, A, B, A] 包含以下组合(1 列 = 1 个组合),请注意组合如何环绕行。

A, A, A, B 
A, A, B, A 
A, B, A, A 
B, A, A, A 

How ever it's allowed for a combination to end up more than 1 time amongst all generated rows but it should be kept at the optimal minimum.如何允许组合在所有生成的行中超过 1 次,但它应该保持在最佳最小值。

How should I go about this programmatically?我应该如何以编程方式 go ?

Are you counting in base 3 ?你在以3为底数吗? with the digits 1, 2, 3 instead of 0, 1, 2.用数字 1、2、3 代替 0、1、2。

If you don't know how to count in base three, let's do it now.如果您不知道如何以三为基数计数,那么现在就开始吧。 0, 1, 2, 10, 11, 12, 20, 21, 22, 100 0、1、2、10、11、12、20、21、22、100

If you want to know what is the number of rows the with N digits then the answer is 3^N .如果您想知道N位数的行数是多少,那么答案是3^N

If you want to know what sequence you have at a given row of a given length at a given position (the first position is zero) in the sorted list you can use the following function如果您想知道排序列表中给定 position(第一个 position 为零)的给定长度的给定行的序列,您可以使用以下 ZC1C425268E68385D1AB4ZZC17A94F1

def row(k, N):
    d = []
    assert(k < 3**N)
    for _ in range(N):
        k,r = divmod(k, 3)
        d.append(r+1)
    return ''.join(str(di) for di in d[::-1])

An easy to verify row(1, 3)='112' is the second term in of the rows with lenght 3. A not so easy to verify is that the billionth term of length 25 is given by row(10**9-1, 25)='1111113231311311132121111' .易于验证的row(1, 3)='112'是长度为 3 的行中的第二项。不太容易验证的是长度为 25 的第十亿项由row(10**9-1, 25)='1111113231311311132121111'

Using generic symbols使用通用符号

If you want to return a list of arbitrary objects (not necessarily three) it is just changing the way the output is mapped.如果要返回任意对象的列表(不一定是三个),它只是改变 output 的映射方式。

def row(k, symbols, N):
    d = []
    B = len(symbols)
    assert(k < B**N)
    for _ in range(N):
        k,r = divmod(k, B)
        d.append(symbols[r])
    return d[::-1];

Using it使用它

print(row(1, ['red', 'green', 'blue'], 6))
print(row(100, ['red', 'green', 'blue'], 6))
> ['red', 'red', 'red', 'red', 'red', 'green']
> ['red', 'green', 'red', 'blue', 'red', 'green']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM