~quf/computers-are-fast-2020

computers-are-fast-2020/src/06.c -rw-r--r-- 1.5 KiB
6f56515eLukas Himbert Draw the rest of the fine owl. 1 year, 7 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <stdio.h>
#include <stdbool.h>
#include <errno.h>
#include <string.h>
#include <limits.h>

#define ANSWERS_ALL_INIT 0x03ffffff /* bits 0 to 25 set */

unsigned count_ones(unsigned long x) {
  unsigned sum = 0;
  for (size_t i = 0; i < 26; ++i) {
    sum += (x >> i) & 1;
  }
  return sum;
}

int main(void) {
  unsigned sum1 = 0;
  unsigned sum2 = 0;

  unsigned long answers_any = 0;
  unsigned long answers_all = ANSWERS_ALL_INIT;
  bool group_empty = true;

  while (1) {
    char buf[28] = { 0, };
    char *ret = fgets(buf, sizeof buf, stdin);
    if (ret == NULL || strlen(buf) == 0 || (strlen(buf) == 1 && buf[0] == '\n')) {
      /* end of group, end of file, or error */
      if (!group_empty) {
        /* update sum */
        group_empty = true;
        sum1 += count_ones(answers_any);
        sum2 += count_ones(answers_all);
        answers_any = 0;
        answers_all = ANSWERS_ALL_INIT;
      }
      if (ret == NULL) {
        /* EOF */
        if (ferror(stdin)) {
          fprintf(stderr, "Input error: %s.\n", strerror(errno));
          return 1;
        }
        break;
      }
    }
    else {
      /* got answer line */
      group_empty = false;
      unsigned long answers = 0;
      for (size_t i = 0; buf[i]; ++i) {
        if ('a' <= buf[i] && buf[i] <= 'z') {
          answers |= ((unsigned long) 1) << (buf[i] - 'a');
        }
      }
      answers_any |= answers;
      answers_all &= answers;
    }
  }

  printf("%u\n", sum1);
  printf("%u\n", sum2);

  return 0;
}