diff options
Diffstat (limited to '01.c')
-rw-r--r-- | 01.c | 79 |
1 files changed, 79 insertions, 0 deletions
@@ -0,0 +1,79 @@ +#include <stdlib.h> +#include <stdio.h> +#include "input.h" + +#define INPUT "input/01.txt" +#define EXPECTED1 70369L +#define EXPECTED2 203002L + +void part1(struct input_str* input) { + // compute max calories + long max_calories = 0; + long elf_calories = 0; + for(size_t i = 0; i < input->line_count; i++) { + if(*(input->lines[i]) == '\n') { + if(elf_calories > max_calories) + max_calories = elf_calories; + + elf_calories = 0; + } + int snack_calories = atoi(input->lines[i]); + elf_calories += snack_calories; + } + + // input does not end with new line, so one last check + if(elf_calories > max_calories) + max_calories = elf_calories; + + CHECK(max_calories, EXPECTED1) +} + +void update_max_calories(long elf_calories, long* max1, long* max2, long* max3) { + if(elf_calories > *max1) { + *max3 = *max2; + *max2 = *max1; + *max1 = elf_calories; + } + else if(elf_calories > *max2) { + *max3 = *max2; + *max2 = elf_calories; + } + else if(elf_calories > *max3) { + *max3 = elf_calories; + } +} + +void part2(struct input_str* input) { + // compute max calories + long max_1_calories = 0; + long max_2_calories = 0; + long max_3_calories = 0; + long elf_calories = 0; + for(size_t i = 0; i < input->line_count; i++) { + if(*(input->lines[i]) == '\n') { + update_max_calories(elf_calories, &max_1_calories, &max_2_calories, &max_3_calories); + elf_calories = 0; + } + int snack_calories = atoi(input->lines[i]); + elf_calories += snack_calories; + } + + // input does not end with new line, so one last check + update_max_calories(elf_calories, &max_1_calories, &max_2_calories, &max_3_calories); + + CHECK(max_1_calories + max_2_calories + max_3_calories, EXPECTED2) +} + +int main() { + // read input + struct input_str input; + input_str_read(&input, INPUT); + + // do stuff + part1(&input); + part2(&input); + + // cleanup & exit + input_str_free(&input); + return 0; +} |