mirror of
https://codeberg.org/andyscott/advent-of-code.git
synced 2024-11-13 15:50:48 -05:00
105 lines
2.2 KiB
C
105 lines
2.2 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
// Find badges for part 2
|
|
char find_badge(char group[3][50]) {
|
|
|
|
for (int i = 0; i < strlen(group[0]); i++) {
|
|
for (int j = 0; j < strlen(group[1]); j++) {
|
|
for (int k = 0; k < strlen(group[2]); k++) {
|
|
if (group[0][i] == group[1][j] && group[1][j] == group[2][k]) {
|
|
return group[0][i];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
// Find items for part 1
|
|
char find_item(char *items) {
|
|
|
|
int len = strlen(items);
|
|
int mid = len / 2;
|
|
|
|
for (int i = 0; i < mid; i++) {
|
|
for (int j = mid; j < len; j++) {
|
|
if (items[i] == items[j]) {
|
|
return items[i];
|
|
}
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
// Updates item_sum / badge_sum when match is found
|
|
void update_sum(const char c, int *sum) {
|
|
|
|
if (c > 64 && c < 91) {
|
|
*sum += c - 38;
|
|
} else if (c > 96 && c < 123) {
|
|
*sum += c - 96;
|
|
}
|
|
}
|
|
|
|
int main(int argc, char *argv[]) {
|
|
|
|
if (argc != 2) {
|
|
fprintf(stderr, "USAGE: %s input_file\n", argv[0]);
|
|
return 1;
|
|
}
|
|
|
|
FILE *file = fopen(argv[1], "r");
|
|
if (!file) {
|
|
perror("fopen");
|
|
return 1;
|
|
}
|
|
|
|
char items[50] = {0};
|
|
char group[3][50] = {0};
|
|
int item_sum = 0, badge_sum = 0, idx = 0;
|
|
|
|
while (fgets(items, sizeof items / sizeof *items, file) != NULL) {
|
|
|
|
if (strlen(items) == 1) {
|
|
break;
|
|
}
|
|
|
|
// Part 1 - find misplaced items
|
|
items[strlen(items) - 1] = '\0';
|
|
char match = find_item(items);
|
|
if (!match) {
|
|
fprintf(stderr, "Match not found: %s\n", items);
|
|
}
|
|
|
|
update_sum(match, &item_sum);
|
|
|
|
// Part 2 - find badges among groups of 3
|
|
memcpy(group[idx], items, strlen(items));
|
|
idx++;
|
|
|
|
if (idx == 3) {
|
|
idx = 0;
|
|
char badge = find_badge(group);
|
|
if (!badge) {
|
|
fprintf(stderr,
|
|
"Badge not found among the following group:\n%s\n%s\n%s\n",
|
|
group[0], group[1], group[2]);
|
|
}
|
|
|
|
update_sum(badge, &badge_sum);
|
|
|
|
for (int i = 0; i < sizeof group / sizeof *group; i++) {
|
|
memset(group[i], 0, sizeof group[0] / sizeof *group[0]);
|
|
}
|
|
}
|
|
memset(items, 0, sizeof items / sizeof *items);
|
|
}
|
|
|
|
fclose(file);
|
|
printf("Part 1 - Sum of item priorities: %d\n", item_sum);
|
|
printf("Part 2 - Sum of badge priorities: %d\n", badge_sum);
|
|
|
|
return 0;
|
|
}
|