summaryrefslogtreecommitdiff
path: root/03.c
diff options
context:
space:
mode:
authorVincent Douillet <vincent@vdouillet.fr>2022-12-03 22:00:50 +0100
committerVincent Douillet <vincent@vdouillet.fr>2022-12-03 22:00:50 +0100
commit56d350f318f8cf9b580852b123d505845abad84e (patch)
tree00cc84eb598ef79c213f9b060788dfa2a67ef257 /03.c
parent4382d5aaf86ccfc09c38f5ede0e1fa06beb04684 (diff)
day 3
Diffstat (limited to '03.c')
-rw-r--r--03.c79
1 files changed, 79 insertions, 0 deletions
diff --git a/03.c b/03.c
new file mode 100644
index 0000000..d5b10fd
--- /dev/null
+++ b/03.c
@@ -0,0 +1,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;
+}