Day 4 complete

This commit is contained in:
Andrew Scott 2022-12-15 15:35:21 -05:00
parent 594996acb9
commit 46af70bb90
Signed by: a
GPG key ID: 7CD5A5977E4931C1
2 changed files with 1090 additions and 0 deletions

90
2022/4.c Normal file
View file

@ -0,0 +1,90 @@
#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;
}

1000
2022/4.txt Normal file

File diff suppressed because it is too large Load diff