c 2022 3 part 1
This commit is contained in:
parent
f319dc2cc9
commit
8cc394d67c
78
c/2022/3/problem.c
Normal file
78
c/2022/3/problem.c
Normal file
@ -0,0 +1,78 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "../../lib/aoc.h"
|
||||
|
||||
typedef struct Compartment {
|
||||
char contents[52];
|
||||
} Compartment;
|
||||
|
||||
void print_compartment(Compartment *c) {
|
||||
for (char i = 'a'; i <= 'z'; i++) {
|
||||
printf("%c", i);
|
||||
}
|
||||
for (char i = 'A'; i <= 'Z'; i++) {
|
||||
printf("%c", i);
|
||||
}
|
||||
printf("\n");
|
||||
for (char i = 0; i < 52; i++) {
|
||||
printf("%d", c->contents[i]);
|
||||
}
|
||||
printf("\n\n");
|
||||
}
|
||||
|
||||
Compartment fill_compartment(const char *half) {
|
||||
Compartment compartment;
|
||||
for (char i = 0; i < 52; i++) {
|
||||
compartment.contents[i] = 0;
|
||||
}
|
||||
|
||||
for (int i = 0; i < strlen(half); i++) {
|
||||
char c = half[i];
|
||||
if (c >= 'a' && c <= 'z') {
|
||||
compartment.contents[c - 'a'] = 1;
|
||||
} else {
|
||||
compartment.contents[c - 'A' + 26] = 1;
|
||||
}
|
||||
}
|
||||
fflush(stdout);
|
||||
return compartment;
|
||||
}
|
||||
|
||||
int priority(char *line) {
|
||||
int len = strlen(line);
|
||||
char *second = malloc((len / 2) + 1);
|
||||
strcpy(second, line + (len / 2));
|
||||
line[len / 2] = '\0';
|
||||
|
||||
Compartment c1 = fill_compartment(line);
|
||||
Compartment c2 = fill_compartment(second);
|
||||
|
||||
// print_compartment(&c1);
|
||||
// print_compartment(&c2);
|
||||
|
||||
for (int i = 0; i < 52; i++) {
|
||||
if (c1.contents[i] && c2.contents[i]) {
|
||||
free(second);
|
||||
return i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
free(second);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main() {
|
||||
char *line;
|
||||
|
||||
int sum = 0;
|
||||
while ((line = aoc_read_line()) != NULL) {
|
||||
sum += priority(line);
|
||||
}
|
||||
|
||||
printf("Part 1: %d\n", sum);
|
||||
|
||||
aoc_free();
|
||||
return 0;
|
||||
}
|
Loading…
Reference in New Issue
Block a user