0
votes

I was requested to fill in a structure with all available combinations of 4 variables (colour,shape,nr,p).

All these variables can take 3 values so I have a total of 81 combinations. I will use these combinations later on to create a card game.

The combinations for each:

  • colour : r,g,b
  • shape : d,e,f
  • nr : 1,2,3
  • p : j,k,l

I was advised that 4 loops are sufficient to do this, but can't find out how they should be formed. What I am thinking of is fill in the first 27 positions with a value for colour, then the other 27 positions with colour, and then the rest with another colour.. Then starting to fill in the shape, and after that the nr etc.. But that way I have too many loops and not only 4 that should be sufficient according to the instructions.

This is part of a bigger exercise but if I don't fill in the structure I can't move on to the significant stuff!

What am I missing?

#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..
}
1
Curiously similar but different to this recent question. - Weather Vane
If you want to fill in all 81 permutations you should use four nested loops. - Weather Vane
Wow, i haven't seen this! But since i am really new to programming i can't get to use unions. Also this is homework so can't use more advanced stuff. Thank you for your time in any case! Can you point out one example of the nested loops because it seems that i am totally stuck? R.G. - ritgeo
because the linked question had 4 permutations of each 4 features my answer side-stepped the nested loops, but could have used them. They are shown in an answer to this question, below. - Weather Vane

1 Answers

1
votes

You need 4 nested loops to go through each possible combination (3 * 3 * 3 * 3 == 81). You'll also need 4 fixed arrays of the possible values for each field to iterate through.

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++;
            }
        }
    }
}