summaryrefslogtreecommitdiff
path: root/01bis.c
blob: e2bbb8aefa80869356296ac212a649d018737f81 (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
#include <stdlib.h>
#include <stdio.h>
#include <err.h>
#include "input.h"

#define INPUT "input/01.txt"
#define MAX_ELF 2000
#define EXPECTED1 70369L
#define EXPECTED2 203002L

int cmp_calorie(const void* a, const void* b) {
	return *(int*)b - *(int*)a;
}

int main() {
	// read input
	struct input_str input;
	input_str_read(&input, INPUT);

	// compute each elf calorie count
	long elf_calories[MAX_ELF];
	int elf_count = 0;
	long elf_calorie = 0;
	for(size_t i = 0; i < input.line_count; i++) {
		if(*(input.lines[i]) == '\n') {
			elf_calories[elf_count] = elf_calorie;
			elf_count++;
			if(elf_count >= MAX_ELF)
				err(2, "elf overflow!");
			elf_calorie = 0;
		}
		else {
			int snack_calories = atoi(input.lines[i]);
			elf_calorie += snack_calories;
		}
	}
	elf_calories[elf_count] = elf_calorie;
	elf_count++;
	if(elf_count >= MAX_ELF)
		err(2, "elf overflow!");

	// sort calories from highest to lowest
	qsort(elf_calories, elf_count, sizeof(long), cmp_calorie);

	// part 1
	if(elf_count < 1)
		err(2, "insufficent elves!");
	CHECK(elf_calories[0], EXPECTED1)
	
	// part 2		
	if(elf_count < 3)
		err(2, "insufficent elves!");
	CHECK(elf_calories[0] + elf_calories[1] + elf_calories[2], EXPECTED2)

	// cleanup & exit
	input_str_free(&input);
	return 0;
}