From: Lukáš Jiřiště Date: Sun, 10 Dec 2023 14:07:00 +0000 (+0100) Subject: Add solution to second part of day 9 X-Git-Url: https://git.ljiriste.work/?a=commitdiff_plain;h=a8e6d39be371c52354904e7f1f6049c1db198f23;p=AoC_2023.git Add solution to second part of day 9 --- diff --git a/9/9b.c b/9/9b.c new file mode 100644 index 0000000..5d7b0ae --- /dev/null +++ b/9/9b.c @@ -0,0 +1,114 @@ + +#include "libft.h" +#include +#include +#include + +void ft_vec_free_naive(void *vec) +{ + ft_vec_free(vec, NULL); + return ; +} + +int all_zero(t_vec *seq) +{ + size_t i; + + i = 0; + while (i < seq->size) + { + if (*(int *)ft_vec_access(seq, i) != 0) + return (0); + ++i; + } + return (1); +} + +void add_differences(t_vec *diffs) +{ + size_t i; + t_vec *main; + t_vec seq; + + main = (t_vec *)ft_vec_access(diffs, diffs->size - 1); + ft_vec_init(&seq, sizeof(int)); + i = 0; + while (i < main->size - 1) + { + ft_vec_append(&seq, &(int){*(int *)ft_vec_access(main, i + 1) - *(int *)ft_vec_access(main, i)}); + ++i; + } + ft_vec_append(diffs, &seq); + if (!all_zero(&seq)) + add_differences(diffs); + return ; +} + +int create_prediction(t_vec *diffs) +{ + size_t i; + t_vec *diff_row; + t_vec *cur_row; + int tmp; + + diff_row = (t_vec *)ft_vec_access(diffs, diffs->size - 1); + ft_vec_append(diff_row, &(int){0}); + i = 1; + while (i < diffs->size) + { + cur_row = (t_vec *)ft_vec_access(diffs, diffs->size - (i + 1)); + tmp = *(int *)ft_vec_access(cur_row, 0) - *(int *)ft_vec_access(diff_row, 0); + ft_vec_insert(cur_row, &tmp, 0); + diff_row = cur_row; + ++i; + } + return (tmp); +} + +int predict(const char *history) +{ + t_vec diffs; + t_vec seq; + int res; + + ft_vec_init(&diffs, sizeof(t_vec)); + ft_vec_init(&seq, sizeof(int)); + while (*history) + { + ft_vec_append(&seq, &(int){ft_atoi(history)}); + while (ft_isdigit(*history) || *history == '-') + ++history; + if (*history) + ++history; + } + ft_vec_append(&diffs, &seq); + add_differences(&diffs); + create_prediction(&diffs); + seq = *(t_vec *)ft_vec_access(&diffs, 0); + res = *(int *)ft_vec_access(&seq, 0); + ft_vec_free(&diffs, ft_vec_free_naive); + return (res); +} + +int main(int argc, char **argv) +{ + int fd; + char *history; + long res; + + if (argc != 2) + return (1); + fd = open(argv[1], O_RDONLY); + if (fd < 0) + return (2); + history = get_next_line(fd); + res = 0; + while (history) + { + res += predict(history); + free(history); + history = get_next_line(fd); + } + ft_printf("The resulting sum is %u.\n", res); + return (0); +}