Search code examples
carrayssetcomplement

idiomatic way to construct the complement of an array in C


I'm writing a function that gets passed a pointer to an array of length 4. This array will contain integers 0 <= x <= 52 and I would like to construct an array of length 48 with every integer from da kine that's not in the passed in array. In python this would be

# just included for specificity
cards = [card for card in deck if card not in hand]

in C the best I can do is

int i, j, k, found_flag;
int cards[48];    /* int hand[4] is passed in */

k = 0;
for (i = 0; i < 52; i++) {
  found_flag = 0;
  for (j = 0; j < 4; j++) {
    if (i == hand[j]) {
      found_flag = 1;
      break;
    }
  }
  if (!found_flag) {
      cards[k++] = i;
  }
}

Is this optimal for this circumstance? Generally, is the 'go-to' pattern?


Solution

  • Sure, your example is fine for a hand size of only 4 - it's clear enough. In situations where the arrays were much larger, then more efficient algorithms based on various kinds of sorting could be used.

    For example, a radix sort eliminates the nested loops:

    int i, j;
    int card_in_hand[52] = { 0 };
    int cards[48];    /* int hand[4] is passed in */
    
    for (i = 0; i < 4; i++)
        card_in_hand[hand[i]] = 1;
    
    j = 0;
    for (i = 0; i < 52; i++)
      if (!card_in_hand[i])
          cards[j++] = i;