blob: d5b10fd47dad3bbfe7452e549da81cea8a039b3c (
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 <err.h>
#include <string.h>
#include "input.h"
#define INPUT "input/03.txt"
#define EXPECTED1 7446L
#define EXPECTED2 2646L
void part1(struct input_str* input) {
long priority_sum = 0;
char duplicate_item;
for(size_t i = 0; i < input->line_count; i++) {
int rucksack_size = strlen(input->lines[i]);
int compartment_size = rucksack_size / 2;
for(int j = 0; j < compartment_size; j++) {
for(int k = compartment_size; k <= rucksack_size; k++) {
if(input->lines[i][j] == input->lines[i][k]) {
duplicate_item = input->lines[i][j];
goto found_duplicate;
}
}
}
err(2, "rucksack %ld: no duplicate found", i);
found_duplicate:
if(duplicate_item > 'a')
priority_sum += duplicate_item - 'a' + 1;
else
priority_sum += duplicate_item - 'A' + 27;
}
CHECK(priority_sum, EXPECTED1)
}
void part2(struct input_str* input) {
long priority_sum = 0;
char badge;
// loop on groups of elves
for(size_t i = 0; i < input->line_count; i += 3) {
// loop on first rucksack content
for(size_t j = 0; j <= strlen(input->lines[i]); j++) {
// second rucksack
for(size_t k = 0; k <= strlen(input->lines[i+1]); k++) {
// third rucksack
for(size_t l = 0; l <= strlen(input->lines[i+2]); l++) {
if(input->lines[i][j] == input->lines[i+1][k] && input->lines[i][j] == input->lines[i+2][l]) {
badge = input->lines[i][j];
goto found_bagde;
}
}
}
}
err(2, "rucksack %ld: no badge found", i);
found_bagde:
if(badge > 'a')
priority_sum += badge - 'a' + 1;
else
priority_sum += badge - 'A' + 27;
}
CHECK(priority_sum, 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;
}
|