summaryrefslogtreecommitdiff
path: root/9/part2.c
diff options
context:
space:
mode:
authorBond_009 <bond.009@outlook.com>2020-12-09 10:24:38 +0100
committerBond_009 <bond.009@outlook.com>2020-12-09 10:24:38 +0100
commitd1aefe3ee5b1c38bc00262670fb67b1362fbc61d (patch)
tree950591ed24e450de23e0cd3939eb3a0aecbc4a98 /9/part2.c
parent210ef0b7b90d685a248d5ed493ee502f78524085 (diff)
Add day 9
Diffstat (limited to '9/part2.c')
-rw-r--r--9/part2.c81
1 files changed, 81 insertions, 0 deletions
diff --git a/9/part2.c b/9/part2.c
new file mode 100644
index 0000000..ceab610
--- /dev/null
+++ b/9/part2.c
@@ -0,0 +1,81 @@
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <malloc.h>
+#include <string.h>
+
+#define INPUT_LEN 1000
+#define SEARCH_LEN 25
+
+bool has_sum(uint64_t *cur_num)
+{
+ uint64_t search = *cur_num;
+ uint64_t *p1 = cur_num - SEARCH_LEN;
+ do {
+ uint64_t *p2 = cur_num - SEARCH_LEN;
+ do {
+ if (*p1 + *p2 == search) {
+ return true;
+ }
+ } while (++p2 < cur_num);
+ } while (++p1 < cur_num);
+
+ return false;
+}
+
+int exe_program(const char *filename)
+{
+ FILE *file = fopen(filename, "r");
+
+ // Include space for newline and string terminator
+ char buffer[24] = { 0 };
+
+ uint64_t *nums = malloc(INPUT_LEN * sizeof(uint64_t));
+ size_t num_size = 0;
+
+ while (fgets(buffer, 24, file)) {
+ nums[num_size++] = strtoull(buffer, NULL, 10);
+ }
+
+ fclose(file);
+
+ uint64_t *cur_num = nums + SEARCH_LEN;
+ uint64_t search = -1;
+ do {
+ if (!has_sum(cur_num)) {
+ search = *cur_num;
+ break;
+ }
+ } while (++cur_num < nums + num_size);
+
+ cur_num = nums;
+ do {
+ uint64_t min = __LONG_LONG_MAX__;
+ uint64_t max = 0;
+ uint64_t sum = 0;
+ uint64_t *p1 = cur_num;
+ do {
+ if (*p1 < min) {
+ min = *p1;
+ }
+
+ if (*p1 > max) {
+ max = *p1;
+ }
+
+ sum += *p1;
+
+ if (sum == search) {
+ return min + max;
+ }
+ } while (++p1 < nums + num_size);
+ } while (++cur_num < nums + num_size);
+
+ return -1;
+}
+
+int main(int argc, char *argv[])
+{
+ printf("%i\n", exe_program(argv[argc - 1]));
+}