advent-of-code/2022/6.c

117 lines
2.2 KiB
C
Raw Normal View History

2022-12-23 18:14:26 -05:00
#include <stddef.h>
#include <stdio.h>
// Part 1 - finds and returns the start-of-packet marker, or 0 if none exists
size_t get_pkt_mark(FILE *file) {
size_t pos = 0;
int c = 0, c_arr[4] = {0};
while ((c = fgetc(file)) != EOF) {
if (pos < 4) {
c_arr[pos] = c;
pos++;
continue;
}
int invalid_marker = 0;
size_t len = sizeof c_arr / sizeof *c_arr;
for (size_t i = 0; i < len - 1; i++) {
for (size_t j = i + 1; j < len; j++) {
if (c_arr[i] == c_arr[j]) {
invalid_marker = 1;
}
}
}
if (!invalid_marker) {
return pos;
}
c_arr[0] = c_arr[1];
c_arr[1] = c_arr[2];
c_arr[2] = c_arr[3];
c_arr[3] = c;
pos++;
}
return 0;
}
size_t get_msg_mark(FILE *file) {
size_t pos = 0;
int c = 0, c_arr[14] = {0};
while ((c = fgetc(file)) != EOF) {
if (pos < 14) {
c_arr[pos] = c;
pos++;
continue;
}
int invalid_marker = 0;
size_t len = sizeof c_arr / sizeof *c_arr;
for (size_t i = 0; i < len - 1; i++) {
for (size_t j = i + 1; j < len; j++) {
if (c_arr[i] == c_arr[j]) {
invalid_marker = 1;
}
}
}
if (!invalid_marker) {
return pos;
}
for (size_t i = 0; i < len - 1; i++) {
c_arr[i] = c_arr[i + 1];
}
c_arr[len - 1] = c;
pos++;
}
return 0;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "USAGE: %s input_file\n", argv[0]);
return 1;
}
// Part 1 - find the start-of-packet marker
FILE *file = fopen(argv[1], "r");
if (!file) {
perror("fopen part1");
return 1;
}
size_t pkt_mark = get_pkt_mark(file);
if (!pkt_mark) {
fprintf(stderr, "Start-of-Packet marker not found\n");
} else {
printf("Part 1: Start-of-Packet marker at position %lu\n", pkt_mark);
}
fclose(file);
// Part 2 - find the start-of-message marker
file = fopen(argv[1], "r");
if (!file) {
perror("fopen part2");
return 1;
}
size_t msg_mark = get_msg_mark(file);
if (!msg_mark) {
fprintf(stderr, "Start-of-Message marker not found\n");
} else {
printf("Part 2: Start-of-Message marker at position %lu\n", msg_mark);
}
fclose(file);
return 0;
}