advent-of-code/2022/4.c

91 lines
2.3 KiB
C
Raw Normal View History

2022-12-15 15:35:21 -05:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Assignment {
char *range;
int start;
int end;
};
// Split each line into 2 strings representing the assignment range for each elf
void parse_assignments(char *assignments, struct Assignment *elf1,
struct Assignment *elf2) {
elf1->range = strtok(assignments, ",");
elf2->range = strtok(NULL, ",");
}
// Split each assignment range into a start and end
void parse_sections(struct Assignment *elf) {
elf->start = atoi(strtok(elf->range, "-,"));
elf->end = atoi(strtok(NULL, "-,"));
}
// Count the number of assignments that fully contain the other
void count_subsets(int *count, struct Assignment *elf1,
struct Assignment *elf2) {
if ((elf1->start >= elf2->start && elf1->end <= elf2->end) ||
(elf2->start >= elf1->start && elf2->end <= elf1->end)) {
*count += 1;
}
}
// Count the number of assignments with any overlapping sections
void count_overlaps(int *count, struct Assignment *elf1,
struct Assignment *elf2) {
if ((elf1->start <= elf2->end && elf1->end >= elf2->start) ||
(elf2->start <= elf1->end && elf2->end >= elf1->start)) {
*count += 1;
}
}
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;
}
int part1_count = 0;
int part2_count = 0;
char assignments[16] = {0};
while (fgets(assignments, sizeof assignments / sizeof *assignments, file)) {
if (strlen(assignments) == 1) {
break;
}
struct Assignment elf1;
struct Assignment elf2;
assignments[strlen(assignments) - 1] = '\0';
// split input into starting and ending points
parse_assignments(assignments, &elf1, &elf2);
parse_sections(&elf1);
parse_sections(&elf2);
// Part 1 - count sections that fully are fully contained by another
count_subsets(&part1_count, &elf1, &elf2);
// Part 2 - count all overlapping sections
count_overlaps(&part2_count, &elf1, &elf2);
}
printf("Part 1 - %d ranges fully contain another\n", part1_count);
printf("part 2 - %d assignments overlap\n", part2_count);
fclose(file);
return 0;
}