Skip to content

Instantly share code, notes, and snippets.

@weirddan455
Created December 2, 2022 07:32
Show Gist options
  • Save weirddan455/6b656176ce6d591689dfb4da2b41f7bf to your computer and use it in GitHub Desktop.
Save weirddan455/6b656176ce6d591689dfb4da2b41f7bf to your computer and use it in GitHub Desktop.
Advent of Code Day 2 Part 2
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
typedef enum ParseState
{
OPPONENT,
SPACE,
YOU,
NEWLINE
} ParseState;
int main(void)
{
int fd = open("input", O_RDONLY);
if (fd == -1) {
perror("open");
return -1;
}
char buffer[4096];
ssize_t bytes;
size_t score = 0;
ParseState state = OPPONENT;
char you;
char opponent;
while ((bytes = read(fd, buffer, 4096)) > 0) {
for (ssize_t i = 0; i < bytes; i++) {
switch (state) {
case OPPONENT:
opponent = buffer[i];
state = SPACE;
break;
case SPACE:
state = YOU;
break;
case YOU:
you = buffer[i];
state = NEWLINE;
break;
case NEWLINE:
switch (you) {
case 'X':
switch (opponent) {
case 'A':
score += 3;
break;
case 'B':
score += 1;
break;
case 'C':
score += 2;
break;
default:
fprintf(stderr, "Invalid input\n");
return -1;
}
break;
case 'Y':
score += 3;
switch (opponent) {
case 'A':
score += 1;
break;
case 'B':
score += 2;
break;
case 'C':
score += 3;
break;
default:
fprintf(stderr, "Invalid input\n");
return -1;
}
break;
case 'Z':
score += 6;
switch (opponent) {
case 'A':
score += 2;
break;
case 'B':
score += 3;
break;
case 'C':
score += 1;
break;
default:
fprintf(stderr, "Invalid input\n");
return -1;
}
break;
default:
fprintf(stderr, "Invalid input\n");
return -1;
}
state = OPPONENT;
break;
}
}
}
close(fd);
printf("Score: %lu\n", score);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment