Skip to content

Instantly share code, notes, and snippets.

@weirddan455
Created December 3, 2022 06:27
Show Gist options
  • Save weirddan455/155bbcf51bcc14bfe4bdf39559438025 to your computer and use it in GitHub Desktop.
Save weirddan455/155bbcf51bcc14bfe4bdf39559438025 to your computer and use it in GitHub Desktop.
Advent of Code Day 3 Part 2
#include <fcntl.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.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 buffer[4096];
ssize_t bytes;
size_t answer = 0;
uint64_t bitfield[3];
int rucksack = 0;
memset(bitfield, 0, 3 * sizeof(uint64_t));
while((bytes = read(fd, buffer, 4096)) > 0) {
for (ssize_t i = 0; i < bytes; i++) {
if (buffer[i] == '\n') {
rucksack++;
if (rucksack > 2) {
rucksack = 0;
uint64_t priority = bitfield[0] & bitfield[1] & bitfield[2];
for (int j = 1; j < 53; j++) {
uint64_t test = (uint64_t)1 << j;
if (test & priority) {
answer += j;
break;
}
}
memset(bitfield, 0, 3 * sizeof(uint64_t));
}
} else {
bitfield[rucksack] |= (uint64_t)1 << 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