~quf/computers-are-fast-2020

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

#define MAXSIZE 40
#define MAXSIZE_S "40"

bool check_part1(unsigned i1, unsigned i2, char c, const char *pw) {
  size_t count = 0;
  while (*pw) {
    count += (*pw == c);
    ++pw;
  }
  return (i1 <= count) && (count <= i2);
}

bool check_part2(unsigned i1, unsigned i2, char c, const char *pw) {
  return (pw[i1-1] == c) ^ (pw[i2-1] == c);
}

int main(void) {
  size_t valid_1 = 0;
  size_t valid_2 = 0;
  int ret;
  while (1) {
    unsigned i1;
    unsigned i2;
    char c;
    char pw[MAXSIZE+1];
    if ((ret = scanf("%u-%u %c: %"MAXSIZE_S"s\n", &i1, &i2, &c, pw)) <= 0) {
      break;
    }
    /* input validation */
    if (i1 < 1 || i2 > strlen(pw)) {
      continue;
    }
    /* check */
    valid_1 += (size_t) check_part1(i1, i2, c, pw);
    valid_2 += (size_t) check_part2(i1, i2, c, pw);
  }
  if (ret != EOF) {
    fprintf(stderr, "Error parsing input: %s.\n", strerror(errno));
    return 1;
  }

  printf("%zu\n", valid_1);
  printf("%zu\n", valid_2);

  return 0;
}