From a7c15c246b50daac881905958a83b32ef49eae68 Mon Sep 17 00:00:00 2001 From: Parker Macdonald Date: Sun, 8 Dec 2024 16:44:47 -0700 Subject: [PATCH] not done yet, just commiting so i can get my code on my desktop --- day_2/2.c | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 day_2/2.c diff --git a/day_2/2.c b/day_2/2.c new file mode 100644 index 0000000..677fda7 --- /dev/null +++ b/day_2/2.c @@ -0,0 +1,81 @@ +#include +#include +#include +#include + +typedef struct levels { + size_t mem_size; + size_t size; + unsigned int *data; +} levels_t; + +int main(void) { + FILE *fp = fopen("example", "r"); + + if (fp == NULL) { + perror("input"); + return 1; + } + + char *line = NULL; + size_t size; + + levels_t levels; + levels.mem_size = 10; + levels.size = 0; + levels.data = malloc(sizeof(unsigned int) * levels.mem_size); + + unsigned int sum = 0; + while (getline(&line, &size, fp) > 0) { + char *next = strtok(line, " "); + + while (next != NULL) { + if (levels.size >= levels.mem_size) { + levels.mem_size *= 2; + levels.data = + realloc(levels.data, levels.mem_size * sizeof(unsigned int)); + } + + sscanf(next, "%u", &levels.data[levels.size]); + levels.size++; + + next = strtok(NULL, " "); + } + + bool removed_node = false; + bool safe = true; + int diff = levels.data[1] - levels.data[0]; + int increasing = diff > 0 ? 1 : -1; + for (int i = 1; i < levels.size; i++) { + diff = increasing * (levels.data[i] - levels.data[i - 1]); + + if (diff < 1 || diff > 3) { + if (removed_node) { + safe = false; + break; + } + for (int j = i; j < levels.size; j++) { + levels.data[j - 1] = levels.data[j]; + } + levels.size--; + i = 0; + removed_node = true; + } + } + + if (safe) { + sum++; + } + + levels.size = 0; + } + + free(line); + free(levels.data); + + printf("%u\n", sum); + + fclose(fp); + + return 0; +} \ No newline at end of file