~quf/computers-are-fast-2020

computers-are-fast-2020/src/05.c -rw-r--r-- 1.2 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
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <errno.h>

int main(void) {
  bool assigned[1024] = { 0, };
  unsigned min = 65535;
  unsigned max = 0;

  /* read input and get min and max id */
  char buf[11];
  while (fgets(buf, sizeof buf, stdin) != NULL) {
    unsigned id = 0;
    for (size_t i = 0; buf[i]; ++i) {
      id = id << 1 | (buf[i] == 'B' || buf[i] == 'R');
    }
    if (id > sizeof assigned / sizeof *assigned) {
      fprintf(stderr, "Error: Seat ID too large!\n");
      return 0;
    }
    else {
      assigned[id] = true;
    }
    if (id < min) {
      min = id;
    }
    if (id > max) {
      max = id;
    }
  }
  if (ferror(stdin) || !feof(stdin)) {
    fprintf(stderr, "Input error: %s.\n", strerror(errno));
    return 1;
  }

  /* part 1: print max */
  printf("%u\n", max);

  /* part 2: find empty spot in the middle */
  if (min == 0) {
    min = 1;
  }
  if (max >= (sizeof assigned / sizeof *assigned) - 1) {
    max = (sizeof assigned / sizeof *assigned) - 2;
  }
  for (size_t i = min; i < max; ++i) {
    if (!assigned[i] && assigned[i-1] && assigned[i+1]) {
      printf("%zu\n", i);
      return 0;
    }
  }
  fprintf(stderr, "Error: No seat found.\n");
  return 1;
}