From f71713079959f0541a025e292bfc8bd240e7bbae Mon Sep 17 00:00:00 2001 From: Peter Date: Wed, 1 Dec 2021 23:53:22 +0800 Subject: [PATCH] Day 1 solutions --- .gitignore | 7 ++++++ 1/1-1.c | 21 ++++++++++++++++++ 1/1-2.c | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 92 insertions(+) create mode 100644 .gitignore create mode 100644 1/1-1.c create mode 100644 1/1-2.c diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1518e5d --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +* +!/**/ +!*.* + +*.out +*.swp +.vscode/ diff --git a/1/1-1.c b/1/1-1.c new file mode 100644 index 0000000..6ebb892 --- /dev/null +++ b/1/1-1.c @@ -0,0 +1,21 @@ +#include +#include +#include + +int main(int argc, char const *argv[]) +{ + FILE *p_file = fopen("input", "r"); + char line[50]; + uint increases = 0; + uint previous_depth = 0; + while (fgets(line, sizeof line, p_file) != NULL) + { + if (atoi(line) > previous_depth) + { + increases++; + } + previous_depth = atoi(line); + } + printf("%u\n", increases - 1); + return 0; +} diff --git a/1/1-2.c b/1/1-2.c new file mode 100644 index 0000000..4a0bc64 --- /dev/null +++ b/1/1-2.c @@ -0,0 +1,64 @@ +#include +#include +#include +#include + +#define N_WINDOWS 4 +#define WINDOW_LENGTH 3 + +typedef struct +{ + uint sum; + uint count; + bool written; // IGNORE COMPARISONS AT THE START. +} MEASUREMENT_WINDOW; + +int main(int argc, char const *argv[]) +{ + FILE *p_file = fopen("input", "r"); + char line[50]; + uint increases = 0; + + MEASUREMENT_WINDOW windows[N_WINDOWS]; + + uint i = 0; + while (fgets(line, sizeof line, p_file) != NULL) + { + uint n = atoi(line); + // UPDATE MEASURING WINDOWS + for (size_t j = 0; j < N_WINDOWS; j++) + { + MEASUREMENT_WINDOW *window = &windows[j]; + if ((i - j) % N_WINDOWS == 0) + { + window->count = 0; + window->sum = 0; + window->written = true; + } + if (window->written && window->count < 3) + { + window->sum += n; + window->count++; + } + } + // COMPARE WINDOWS + for (size_t j = 0; j < N_WINDOWS; j++) + { + MEASUREMENT_WINDOW *window = &windows[j]; + // ONE WINDOW IS READY TO BE COMPARED + if (window->count == 3) + { + window->count++; // PREVENT DOUBLE-COMPARE OF WINDOW. + MEASUREMENT_WINDOW last_window = windows[(j + N_WINDOWS - 1) % 4]; + if (last_window.written && window->written && window->sum > last_window.sum) + { + increases++; + } + continue; + } + } + i++; + } + printf("%u\n", increases); + return 0; +}