aoc2023/day1/p2.c

97 lines
3.6 KiB
C

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
int main(int argc, char **argv) {
FILE *input;
char *line = NULL;
size_t line_buf_length = 0;
if (argc == 1 || argv[1][0] == '-')
input = stdin;
else if ((input = fopen(argv[1], "r")) == NULL) {
fprintf(stderr, "Cannot open file %s\n", argv[1]);
return -1;
}
uint64_t calibration_value = 0;
while (getline(&line, &line_buf_length, input) != -1) {
uint64_t current_calibration_value = 0;
int8_t last_digit = 0;
for (size_t i = 0; i < line_buf_length-1; ++i)
if (line[i]>>4 == 0x3) {
if (current_calibration_value == 0)
current_calibration_value = (line[i]&0xf) * 10;
last_digit = line[i]&0xf;
} else {
uint8_t digit = 0;
switch (line[i]) {
case 'o': // 1
if (i+2 <= line_buf_length)
if (line[i+1] == 'n' && line[i+2] == 'e')
digit = 1;
break;
case 't': // 2 3
if (i+2 <= line_buf_length)
if (line[i+1] == 'w' && line[i+2] == 'o') {
digit = 2;
break;
}
if (i+4 <= line_buf_length)
if (line[i+1] == 'h' && line[i+2] == 'r' && line[i+3] == 'e' && line[i+4] == 'e')
digit = 3;
break;
case 'f': // 4 5
if (i+3 <= line_buf_length)
if (line[i+1] == 'o' && line[i+2] == 'u' && line[i+3] == 'r') {
digit = 4;
break;
}
if (i+3 <= line_buf_length)
if (line[i+1] == 'i' && line[i+2] == 'v' && line[i+3] == 'e')
digit = 5;
break;
case 's': // 6 7
if (i+2 <= line_buf_length)
if (line[i+1] == 'i' && line[i+2] == 'x') {
digit = 6;
break;
}
if (i+4 <= line_buf_length)
if (line[i+1] == 'e' && line[i+2] == 'v' && line[i+3] == 'e' && line[i+4] == 'n')
digit = 7;
break;
case 'e': // 8
if (i+4 <= line_buf_length)
if (line[i+1] == 'i' && line[i+2] == 'g' && line[i+3] == 'h' && line[i+4] == 't')
digit = 8;
break;
case 'n': // 9
if (i+3 <= line_buf_length)
if (line[i+1] == 'i' && line[i+2] == 'n' && line[i+3] == 'e')
digit = 9;
break;
}
if (digit != 0) {
if (current_calibration_value == 0)
current_calibration_value = digit * 10;
last_digit = digit;
}
}
if (current_calibration_value != 0)
calibration_value += current_calibration_value + last_digit;
memset(line, 0, line_buf_length);
}
printf("%lu\n", calibration_value);
return 0;
}