From 3c366ab7d15ab6ce0b256202b7d5928397ab69e6 Mon Sep 17 00:00:00 2001 From: Bill Rossi Date: Sun, 1 Dec 2024 00:25:47 -0500 Subject: [PATCH] Dynamically count lines --- c/2024/1/historian_hysteria.c | 18 ++++++++---------- c/lib/aoc.h | 9 +++++++++ 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/c/2024/1/historian_hysteria.c b/c/2024/1/historian_hysteria.c index a80ec5c..cafb41c 100644 --- a/c/2024/1/historian_hysteria.c +++ b/c/2024/1/historian_hysteria.c @@ -4,14 +4,12 @@ #include "../../lib/aoc.h" -// TODO figure this out dynamically -#define ARRAY_SIZE 1000 - int main() { char *line; + int line_count = aoc_line_count(); - int left[ARRAY_SIZE]; - int right[ARRAY_SIZE]; + int left[line_count]; + int right[line_count]; int index = 0; while ((line = aoc_read_line()) != NULL) { @@ -22,12 +20,12 @@ int main() { index++; } - qsort(left, ARRAY_SIZE, sizeof(int), aoc_sort_int); - qsort(right, ARRAY_SIZE, sizeof(int), aoc_sort_int); + qsort(left, line_count, sizeof(int), aoc_sort_int); + qsort(right, line_count, sizeof(int), aoc_sort_int); int sum = 0; - for (int i = 0; i < ARRAY_SIZE; i++) { + for (int i = 0; i < line_count; i++) { sum += abs(left[i] - right[i]); } @@ -36,9 +34,9 @@ int main() { int similarity_score = 0; int j = 0; - for (int i = 0; i < ARRAY_SIZE; i++) { + for (int i = 0; i < line_count; i++) { int right_count = 0; - for (; j < ARRAY_SIZE; j++) { + for (; j < line_count; j++) { if (left[i] == right[j]) right_count++; else if (left[i] < right[j]) break; } diff --git a/c/lib/aoc.h b/c/lib/aoc.h index 8ab52a9..aac3147 100644 --- a/c/lib/aoc.h +++ b/c/lib/aoc.h @@ -54,6 +54,15 @@ void aoc_free(void) { free(read_line_buffer); } +int aoc_line_count(void) { + if (input_buffer == NULL) aoc_read_input(); + + int count = 0; + for (int i = 0; i < strlen(input_buffer); i++) { + if (input_buffer[i] == '\n') count++; + } + return count; +} int aoc_sort_int(const void *a, const void *b) { return *(int*) a - *(int*) b;