Skip to content

Instantly share code, notes, and snippets.

@weirddan455
Created December 3, 2022 06:26
Show Gist options
  • Save weirddan455/d2acf114e443cbbd749088fe1b2c2839 to your computer and use it in GitHub Desktop.
Save weirddan455/d2acf114e443cbbd749088fe1b2c2839 to your computer and use it in GitHub Desktop.
Advent of Code Day 3 Part 1
#include <fcntl.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
static char get_priority(char c)
{
if (c >= 'a' && c <= 'z') {
return c - 96;
} else if (c >= 'A' && c <= 'Z') {
return c - 38;
} else {
fprintf(stderr, "Invalid input\n");
exit(-1);
}
}
int main(void)
{
int fd = open("input", O_RDONLY);
if (fd == -1) {
perror("open");
return -1;
}
char line[128];
char buffer[4096];
bool priorities[53];
ssize_t bytes;
int line_index = 0;
size_t answer = 0;
while((bytes = read(fd, buffer, 4096)) > 0) {
for (ssize_t i = 0; i < bytes; i++) {
if (buffer[i] == '\n') {
if (line_index % 2 != 0) {
fprintf(stderr, "Odd line length\n");
return -1;
}
memset(priorities, 0, 53 * sizeof(bool));
int compartment2 = line_index / 2;
for (int j = 0; j < compartment2; j++) {
priorities[line[j]] = true;
}
for (int j = compartment2; j < line_index; j++) {
if (priorities[line[j]]) {
answer += line[j];
break;
}
}
line_index = 0;
} else {
line[line_index++] = get_priority(buffer[i]);
}
}
}
printf("Answer: %ld\n", answer);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment