~quf/computers-are-fast-2020

computers-are-fast-2020/src/01.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
66
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdbool.h>

#define N 2020

void part1(const unsigned int *numbers, const bool *lookup_table, size_t len) {
  for (size_t i = 0; i < len; ++i) {
    unsigned int x = numbers[i];
    if (lookup_table[N - x]) {
      printf("%ld\n", (long)x*(N-(long)x));
      break;
    }
  }
}

void part2(const unsigned int *numbers, const bool *lookup_table, size_t len) {
  for (size_t i = 0; i < len; ++i) {
    unsigned int x = numbers[i];
    for (size_t j = i; j < len; ++j) {
      unsigned int y = numbers[j];
      unsigned int tmp = x + y;
      if (tmp > N) {
        continue;
      }
      if (lookup_table[N - tmp]) {
        printf("%lld\n", (long long)x*(long long)y*(N-(long long)tmp));
        return;
      }
    }
  }
}

int main(void) {
  /* read input */
  size_t len = 0;
  unsigned int numbers[300] = { 0, };
  bool lookup_table[N+1] = { 0, };
  {
    int ret;
    unsigned int n;
    while ((ret = scanf("%u\n", &n)) > 0) {
      /* input validation to avoid overflow */
      if (n > N) {
        continue;
      }
      numbers[len++] = n;
      lookup_table[n] = true;
      if (len > sizeof numbers / sizeof *numbers) {
        fprintf(stderr, "Error: Input too large.\n");
        return 1;
      }
    }
    if (ret != EOF) {
      fprintf(stderr, "Error parsing input: %s.\n", strerror(errno));
      return 1;
    }
  }

  /* run search */
  part1(numbers, lookup_table, len);
  part2(numbers, lookup_table, len);

  return 0;
}