假设我有四套:
set1 = {A, a}
set2 = {B, b}
set3 = {C, c}
set4 = {D, d}
现在我需要所有元素的独特组合(无论以哪种顺序排列),但不包括其中一组。例如,不考虑 set4 ,我需要这些组合:
ABC
AbC
ABc
Abc
aBC
abC
aBc
abc
我试图将这些集合排列为矩阵:
char matrix_calc[2][4] = {
{'A', 'B', 'C', 'D'},
{'a', 'b', 'c', 'd'},
};
我写这段代码是为了找到组合:
uint8_t excluded = 3; // index of the column which has to be excluded
for (i = 0; i < 4; i++) {
if (i != excluded) {
for (x = 0; x < 2; x++) {
for (j = i + 1; j < 4; j++) {
if (j != excluded) {
for (t = 0; t < 2; t++) {
for (k = j + 1; k < 4; k++) {
if (k != excluded) {
for (z = 0; z < 2; z++) {
printf("%c %c %c\n",
matrix_calc[x][i],
matrix_calc[t][j],
matrix_calc[z][k]);
}
}
}
}
}
}
}
}
}
代码有效,但它不灵活,而且似乎很昂贵(就速度而言)。例如,如果集合的数量增加,我必须经常更改代码(我将在其他 for loops 中失去自己。)
例如,如果我有5组而不是4组,我有以下代码:
for (i = 0; i < 5; i++) {
if (i != excluded) {
for (x = 0; x < 2; x++) {
for (j = i + 1; j < 5; j++) {
if (j != excluded) {
for (t = 0; t < 2; t++) {
for (k = j + 1; k < 5; k++) {
if (k != excluded) {
for (z = 0; z < 2; z++) {
for (m = k + 1; m < 5; m++) {
if (m != excluded) {
for (w = 0; w < 2; w++) {
printf("%c %c %c %c\n",
matrix_calc[x][i],
matrix_calc[t][j],
matrix_calc[z][k],
matrix_calc[w][m]);
}
}
}
}
}
}
}
}
}
}
}
}
是否有更有效(和干净)的方式?