-
Notifications
You must be signed in to change notification settings - Fork 0
/
day9.c
65 lines (61 loc) · 1.69 KB
/
day9.c
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 "numbers.h"
#include <stdbool.h>
#include <assert.h>
#include <stdlib.h>
#include <stdint.h>
bool has_comb(int input, int64_t * numbers, size_t len) {
for (int i = 0 ; i < len; i++)
for (int j = i+1 ; j < len; j++) {
int64_t sum = numbers[i] + numbers[j];
if (sum == input) {
return true;
}
sum = 0;
}
return false;
}
int64_t day9_1(size_t preamble, int64_t * numbers, size_t len) {
assert (len > preamble);
size_t start = 0;
for (int i = preamble ; i < len; i++, start++) {
if (!has_comb(numbers[i], numbers+start, preamble)) {
printf("missing number- %ld\n", numbers[i]);
return numbers[i];
}
}
return -1;
}
void day9_2(int64_t missing, int64_t * numbers, size_t len) {
for (int i = 0 ; i < len; i++) {
int64_t smallest = numbers[i];
int64_t largest = numbers[i];
int64_t sum = numbers[i];
for (int j = i+1 ; j < len; j++) {
sum += numbers[j]; // keep adding
if (numbers[j] < smallest) smallest = numbers[j];
if (numbers[j] > largest) largest = numbers[j];
if (sum == missing) {
printf("code: %ld\n", smallest + largest);
return;
} else if (sum > missing) {
break; // we can stop this and get to the next baseline
}
// add another number to the sum.
}
}
printf("nothing found\n");
}
int main() {
numbers_t nums = {0};
char * filename = "day9_input.txt";
numbers_from_file(filename, &nums);
printf("%zu", nums.len);
for (int i = 0 ; i < nums.len; i++) {
printf("%ld\n", nums.numbers[i]);
}
int64_t missing = day9_1(25, nums.numbers, nums.len);
assert(missing != -1);
day9_2(missing, nums.numbers, nums.len);
numbers_free(&nums);
return 0; }