aoc2023/day1/p1.c

42 lines
1.0 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_length = 0;
if (argc == 1 || argv[1][0] == '-')
input = stdin;
else if ((input = fopen(argv[1], "r")) == NULL) {
printf("Cannot open file %s\n", argv[1]);
return -1;
}
int32_t calibration_value = 0;
while (getline(&line, &line_length, input) != -1) {
int32_t current_calibration_value = -1;
int8_t last_digit = 0;
for (size_t i = 0; i < line_length-1; ++i) {
if (line[i]>>4 == 0x3) {
if (current_calibration_value == -1)
current_calibration_value = (line[i]&0xf) * 10;
last_digit = line[i]&0xf;
}
}
if (current_calibration_value != -1)
calibration_value += current_calibration_value + last_digit;
memset(line, 0, line_length);
}
printf("%d\n", calibration_value);
return 0;
}