Created
December 14, 2022 03:35
-
-
Save weirddan455/20e3b5737d58330681807dd3d4e6d379 to your computer and use it in GitHub Desktop.
Advent of Code Day 13 Part 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdbool.h> | |
#include <stdlib.h> | |
#include <stdio.h> | |
typedef struct Packet | |
{ | |
int *data; | |
size_t size; | |
size_t capacity; | |
size_t num_lists; | |
} Packet; | |
static bool is_num(char c) | |
{ | |
return c >= '0' && c <= '9'; | |
} | |
static void add_packet(Packet *packet, int i) | |
{ | |
if (packet->size >= packet->capacity) { | |
packet->capacity *= 2; | |
packet->data = realloc(packet->data, packet->capacity * sizeof(int)); | |
if (packet->data == NULL) { | |
fprintf(stderr, "realloc failed\n"); | |
exit(-1); | |
} | |
} | |
packet->data[packet->size] = i; | |
packet->size += 1; | |
} | |
static void parse_packet(FILE *file, Packet *packet) | |
{ | |
char buffer[512]; | |
if (fgets(buffer, 512, file) == NULL) { | |
fprintf(stderr, "Unexpected end of file\n"); | |
exit(-1); | |
} | |
packet->size = 0; | |
packet->num_lists = 0; | |
char *ptr = buffer; | |
while (*ptr != '\n') { | |
if (is_num(*ptr)) { | |
add_packet(packet, strtol(ptr, &ptr, 10)); | |
} else if (*ptr == '[') { | |
packet->num_lists += 1; | |
ptr += 1; | |
} else { | |
ptr += 1; | |
} | |
} | |
} | |
static bool compare_packets(Packet *p1, Packet *p2) | |
{ | |
size_t smallest; | |
if (p1->size == 0 && p2->size == 0) { | |
return p1->num_lists <= p2->num_lists; | |
} | |
if (p1->size < p2->size) { | |
smallest = p1->size; | |
} else { | |
smallest = p2->size; | |
} | |
for (size_t i = 0; i < smallest; i++) { | |
if (p1->data[i] < p2->data[i]) { | |
return true; | |
} else if (p1->data[i] > p2->data[i]) { | |
return false; | |
} | |
} | |
return p1->size <= p2->size; | |
} | |
int main(void) | |
{ | |
FILE *file = fopen("input", "r"); | |
if (file == NULL) { | |
perror("fopen"); | |
return -1; | |
} | |
Packet p1; | |
Packet p2; | |
p1.capacity = 16; | |
p1.size = 0; | |
p1.data = malloc(p1.capacity * sizeof(int)); | |
if (p1.data == NULL) { | |
fprintf(stderr, "malloc failed\n"); | |
return -1; | |
} | |
p2.capacity = 16; | |
p2.size = 0; | |
p2.data = malloc(p2.capacity * sizeof(int)); | |
if (p2.data == NULL) { | |
fprintf(stderr, "malloc failed\n"); | |
return -1; | |
} | |
int pair = 1; | |
int answer = 0; | |
do { | |
parse_packet(file, &p1); | |
parse_packet(file, &p2); | |
if (compare_packets(&p1, &p2)) { | |
printf("Pair %d: Correct\n", pair); | |
answer += pair; | |
} else { | |
printf("Pair: %d: Incorrect\n", pair); | |
} | |
pair += 1; | |
} while (getc(file) != EOF); | |
printf("Answer: %d\n", answer); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment