summaryrefslogtreecommitdiff
path: root/01.c
blob: 7aba562a11e5d0b625020618f37b65509da592f2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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;
}