Add a read-line-by-line function

This commit is contained in:
Bill Rossi 2024-11-30 06:03:26 -05:00
parent 5af0f941e9
commit c6e004354d
2 changed files with 30 additions and 21 deletions

View File

@ -5,28 +5,16 @@
#include "../../lib/aoc.h"
int main() {
char *input = aoc_read_input();
char *seek = input;
int current_cals = 0;
int current_elf = 0;
int max_elf = 0;
int second_max_elf = 0;
int third_max_elf = 0;
while (seek != NULL) {
char *double_line_break = strstr(seek, "\n\n");
if (double_line_break == NULL) {
seek = NULL;
} else {
*double_line_break = '\0';
char *line = strtok(seek, "\n");
while (line != NULL) {
current_cals = atoi(line);
current_elf += current_cals;
line = strtok(NULL, "\n");
}
char *line;
while ((line = aoc_read_line()) != NULL) {
if (strlen(line) == 0) {
if (current_elf > max_elf) {
int z = current_elf;
current_elf = max_elf;
@ -46,16 +34,15 @@ int main() {
}
current_elf = 0;
seek = double_line_break + 1;
*seek = '\0';
seek = seek + 1;
} else {
current_cals = atoi(line);
current_elf += current_cals;
}
}
printf("Part 1: %d\n", max_elf);
printf("Part 2: %d\n", max_elf + second_max_elf + third_max_elf);
free(input);
aoc_free();
return 0;
}

View File

@ -4,9 +4,11 @@
#define INITIAL_BUFFER_SIZE 2
char *input_buffer;
char *aoc_read_input(void) {
int buffer_size = INITIAL_BUFFER_SIZE;
char *input_buffer = malloc(buffer_size);
input_buffer = malloc(buffer_size);
int chars_read = read(STDIN_FILENO, input_buffer, buffer_size);
char *buffer_position = &input_buffer[chars_read];
@ -20,3 +22,23 @@ char *aoc_read_input(void) {
input_buffer[chars_read] = 0;
return input_buffer;
}
char *seek = NULL;
char *aoc_read_line(void) {
if (input_buffer == NULL) aoc_read_input();
if (seek == NULL) seek = input_buffer;
char *line_break = strstr(seek, "\n");
if (line_break == NULL) return NULL;
*line_break = '\0';
char *token = seek;
seek = line_break + 1;
return token;
}
void aoc_free(void) {
free(input_buffer);
}