我被要求填写一个包含 4 个变量(颜色、形状、nr、p)的所有可用组合的结构。
所有这些变量都可以取 3 个值,所以我总共有 81 种组合。 稍后我将使用这些组合来创建纸牌游戏。
每种组合:
- 颜色:r、g、b
- 形状:d、e、f
- 编号:1,2,3
- p:j、k、l
我被告知 4 个循环就足以做到这一点,但无法找出它们应该如何形成。我想到的是用颜色值填充前 27 个位置,然后用颜色填充其他 27 个位置,然后用另一种颜色填充其余位置。然后开始填充形状,然后是 nr 等。 。 但这样我就有了太多的循环,而不仅仅是 4 个,根据说明应该足够了。
这是更大练习的一部分,但如果我不填写结构,我就无法继续讨论重要的内容!
我错过了什么?
#include <stdio.h>
#include <stdlib.h>
int i;
typedef struct {
unsigned char colour;
unsigned char shape;
unsigned char nr;
unsigned char p;
} CARDS;
int main()
{
CARDS cards[81];
for (i=0;i<27;i++)
cards[i].colour='r';
for(i=27;i<54;i++)
cards[i].colour='g';
for (i=54;i<81;i++)
cards[i].colour='b';
for (i=0;i<6)
cards[i].shape = 'd';
for (i=0;i<12)
cards[i].shape = 'e';
// a lot more loops..
}
最佳答案
您需要 4 个嵌套循环来遍历每种可能的组合 (3 * 3 * 3 * 3 == 81)。您还需要 4 个固定数组,其中包含要迭代的每个字段的可能值。
char color_list[] = {'r','g','b'};
char shape_list[] = {'d','e','f'};
char nr_list[] = {'1','2','3'};
char p_list[] = {'j','k','l'};
CARDS cards[81];
int current = 0;
int i,j,k,l;
for (i=0; i<3; i++) {
for (j=0; j<3; j++) {
for (k=0; k<3; k++) {
for (l=0; l<3; l++) {
cards[current].colour = color_list[i];
cards[current].shape = shape_list[j];
cards[current].nr = nr_list[k];
cards[current].p = p_list[l];
current++;
}
}
}
}
关于c - 使用所有可用组合初始化结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41290711/