From a25485836775f97de160d47adc75d6f9d5f7f74c Mon Sep 17 00:00:00 2001 From: =?utf8?q?Luk=C3=A1=C5=A1=20Ji=C5=99i=C5=A1t=C4=9B?= Date: Sun, 3 Dec 2023 20:49:28 +0100 Subject: [PATCH] Add solution to second part (bonus) of day 1 --- 1/1b.c | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 1/1b.c diff --git a/1/1b.c b/1/1b.c new file mode 100644 index 0000000..21e134f --- /dev/null +++ b/1/1b.c @@ -0,0 +1,74 @@ + +#include +#include +#include +#include "libft.h" + +char is_spelled_digit(char *str) +{ + const char *const digits[] = {"one", "two", "three", "four", "five", + "six", "seven", "eight", "nine", NULL}; + size_t i; + + i = 0; + while (digits[i]) + { + if (!ft_strncmp(str, digits[i], ft_strlen(digits[i]))) + { + return ('0' + i + 1); + } + ++i; + } + return (0); +} + +int line_value(char *line) +{ + char two_digit[2]; + size_t i; + + i = 0; + while (!ft_isdigit(line[i]) && !is_spelled_digit(line + i)) + ++i; + if (ft_isdigit(line[i])) + two_digit[0] = line[i]; + else + two_digit[0] = is_spelled_digit(line + i); + while(line[i]) + ++i; + while (!ft_isdigit(line[i]) && !is_spelled_digit(line + i)) + --i; + if (ft_isdigit(line[i])) + two_digit[1] = line[i]; + else + two_digit[1] = is_spelled_digit(line + i); + return (ft_atoi(two_digit)); +} + +int main(int argc, char **argv) +{ + char *line; + int fd; + int result; + + if (argc != 2) + { + return (1); + } + fd = open(argv[1], O_RDONLY); + if (fd < 0) + { + return (2); + } + result = 0; + line = get_next_line(fd); + while (line) + { + result += line_value(line); + free(line); + line = get_next_line(fd); + } + ft_printf("The calibration sum is %i.\n", result); + close(fd); + return (0); +} -- 2.30.2