79 lines
1.9 KiB
C
79 lines
1.9 KiB
C
|
#include <ctype.h>
|
||
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <string.h>
|
||
|
|
||
|
static char *strrev(char *to_reverse) {
|
||
|
size_t length = strlen(to_reverse);
|
||
|
int position = length - 1;
|
||
|
char *reversed = malloc((1 + length) * sizeof(char));
|
||
|
|
||
|
while (position >= 0) {
|
||
|
*reversed = to_reverse[position];
|
||
|
reversed++;
|
||
|
position--;
|
||
|
}
|
||
|
*reversed = '\0';
|
||
|
reversed = reversed - length;
|
||
|
|
||
|
return reversed;
|
||
|
}
|
||
|
|
||
|
static char first_digit(char *line) {
|
||
|
while (*line != '\0' && !isdigit(*line)) {
|
||
|
line++;
|
||
|
}
|
||
|
|
||
|
if (*line != '\0') {
|
||
|
return *line;
|
||
|
} else {
|
||
|
return 0;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
static char *read_line(FILE *input_file) {
|
||
|
unsigned int max_length = 16;
|
||
|
unsigned int current_length = 0;
|
||
|
char *line = malloc(max_length * sizeof(char));
|
||
|
int current_char = fgetc(input_file);
|
||
|
|
||
|
while (current_char != EOF && current_char != '\n') {
|
||
|
if (current_length == max_length) {
|
||
|
max_length *= 2;
|
||
|
line = realloc(line, max_length * sizeof(char));
|
||
|
}
|
||
|
|
||
|
line[current_length] = current_char;
|
||
|
current_length++;
|
||
|
current_char = fgetc(input_file);
|
||
|
}
|
||
|
|
||
|
if (current_length == max_length) {
|
||
|
line = realloc(line, (max_length + 1) * sizeof(char));
|
||
|
}
|
||
|
line[current_length] = '\0';
|
||
|
|
||
|
return line;
|
||
|
}
|
||
|
|
||
|
unsigned int get_calibration_sum(FILE *input_file) {
|
||
|
unsigned int sum = 0;
|
||
|
char *current_line, *reversed_line;
|
||
|
char intermediate_buffer[3];
|
||
|
intermediate_buffer[2] = '\0';
|
||
|
|
||
|
while (!feof(input_file)) {
|
||
|
current_line = read_line(input_file);
|
||
|
reversed_line = strrev(current_line);
|
||
|
if (*current_line != '\0') {
|
||
|
intermediate_buffer[0] = first_digit(current_line);
|
||
|
intermediate_buffer[1] = first_digit(reversed_line);
|
||
|
sum += atoi(intermediate_buffer);
|
||
|
}
|
||
|
free(reversed_line);
|
||
|
free(current_line);
|
||
|
}
|
||
|
|
||
|
return sum;
|
||
|
}
|