Search code examples
c++coding-style

Making following C++ code concise and efficient


I have an array of 52 elements, and each 13 elements need to have value from 1-13

Example:

// Referring arr to an array of 52 elements


arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
...
arr[10] = 11;
arr[11]] = 12;
arr[12] = 13;
arr[13] = 1;

and so on...

The code that I came up with has 4 for loops that loop from 1-13 each time, I think it's very inefficient.

int j = 1;  
    for(int i = 0; i < 13; i++){
        deck[i].suit = 'H';
        deck[i].value = j;
        j++;
    }
    j = 1;
    for(int i = 13; i < 26; i++){
        deck[i].suit = 'D';
        deck[i].value = j;
        j++;
    }
    j = 1;
    for(int i = 26; i < 39; i++){
        deck[i].suit = 'S';
        deck[i].value = j;
        j++;
    }
    j = 1;
    for(int i = 39; i <= 51; i++){
        deck[i].suit = 'C';
        deck[i].value = j;
        j++;
    }

Solution

  • You're right, you could do way better:

    char suits[] = "HDSC";
    
    for (int i = 0; i < 52; ++i) {
        deck[i].value = (i % 13) + 1; // this is a number from [1,13]
        deck[i].suit = suits[i / 13]; // i/13 is a number from [0,4)
    }