aoc2023/day1/p1.c

41 lines
1.0 KiB
C
Raw Normal View History

2023-12-02 17:34:17 +04:00
#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;
2023-12-06 05:18:43 +04:00
size_t line_buf_length = 0;
2023-12-02 17:34:17 +04:00
if (argc == 1 || argv[1][0] == '-')
input = stdin;
else if ((input = fopen(argv[1], "r")) == NULL) {
2023-12-06 05:18:43 +04:00
fprintf(stderr, "Cannot open file %s\n", argv[1]);
2023-12-02 17:34:17 +04:00
return -1;
}
2023-12-06 05:18:43 +04:00
uint64_t calibration_value = 0;
2023-12-02 17:34:17 +04:00
2023-12-06 05:18:43 +04:00
while (getline(&line, &line_buf_length, input) != -1) {
int64_t current_calibration_value = -1;
uint8_t last_digit = 0;
2023-12-02 17:34:17 +04:00
2023-12-06 05:18:43 +04:00
for (size_t i = 0; i < line_buf_length-1; ++i)
2023-12-02 17:34:17 +04:00
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;
2023-12-06 05:18:43 +04:00
memset(line, 0, line_buf_length);
2023-12-02 17:34:17 +04:00
}
2023-12-06 05:18:43 +04:00
printf("%lu\n", calibration_value);
2023-12-02 17:34:17 +04:00
return 0;
}