From 6493cbdd74d0ee303cb28d3403cfaee7130d7d00 Mon Sep 17 00:00:00 2001 From: Hippolyte Chauvin Date: Sun, 3 Dec 2023 22:39:44 +0100 Subject: [PATCH] =?UTF-8?q?Ajout=20:=20algorithme=20permettant=20de=20r?= =?UTF-8?q?=C3=A9soudre=20le=20jour=201?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/calibration.c | 80 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 src/calibration.c diff --git a/src/calibration.c b/src/calibration.c new file mode 100644 index 0000000..81d5117 --- /dev/null +++ b/src/calibration.c @@ -0,0 +1,80 @@ +#include +#include +#include +#include + +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); + + printf("sum: %d\n", sum); + } + + return sum; +}