-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday1.c
88 lines (73 loc) · 1.84 KB
/
day1.c
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
80
81
82
83
84
85
86
87
88
// ----------------------------------------------------------------------------
// Advent of Code 2022 - Day 1
// Dale Whinham
//
// $ gcc day1.c -Wall -Wextra -Wpedantic -Werror -o day1
// $ ./day1
// ----------------------------------------------------------------------------
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "util.h"
#define INPUT_FILE "input/day1.txt"
typedef struct
{
uint32_t index;
uint32_t calories;
} elf_t;
int main()
{
size_t size;
char* text = read_file(INPUT_FILE, &size);
if (text == NULL)
return EXIT_FAILURE;
elf_t elves[3] = {0};
uint32_t elf_current = 1;
uint32_t cal_current = 0;
char* p = text, *p2 = text;
while (p < text + size)
{
// Find next newline and terminate it
while (p2 < text + size && *p2 != '\n')
++p2;
*p2++ = '\0';
// Convert string to integer
cal_current += atoi(p);
// Two consecutive newlines = next elf
if (*p2 == '\n')
{
for (size_t i = 0; i < ARRAY_SIZE(elves); ++i)
{
if (cal_current > elves[i].calories)
{
elves[i].index = elf_current;
elves[i].calories = cal_current;
break;
}
}
cal_current = 0;
++p2;
++elf_current;
}
p = p2;
}
puts
(
"Top 3 elves:\n"
"============"
);
uint32_t total_calories = 0;
for (size_t i = 0; i < ARRAY_SIZE(elves); ++i)
{
printf("#%3d: %d kcal\n", elves[i].index, elves[i].calories);
total_calories += elves[i].calories;
}
printf
(
"------------\n"
"Total: %d kcal\n", total_calories
);
free(text);
return EXIT_SUCCESS;
}