Add solution to second part of day 4
authorLukáš Jiřiště <gymnazium.jiriste@gmail.com>
Mon, 4 Dec 2023 19:09:24 +0000 (20:09 +0100)
committerLukáš Jiřiště <gymnazium.jiriste@gmail.com>
Wed, 6 Dec 2023 10:17:28 +0000 (11:17 +0100)
4/4b.c [new file with mode: 0644]

diff --git a/4/4b.c b/4/4b.c
new file mode 100644 (file)
index 0000000..b5f8e92
--- /dev/null
+++ b/4/4b.c
@@ -0,0 +1,119 @@
+
+#include <stdlib.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include "libft.h"
+
+#define WINNING_NUM 10
+#define NUMBERS_NUM 25
+#define GAMES 204
+
+struct s_record
+{
+       int     score;
+       int     copies;
+};
+typedef struct s_record        t_record;
+
+int    is_winning(int number, int winning[WINNING_NUM])
+{
+       int     i;
+
+       i = 0;
+       while (i < WINNING_NUM)
+               if (number == winning[i++])
+                       return (1);
+       return (0);
+}
+
+int    score(const char *game)
+{
+       int     result;
+       int     winning[WINNING_NUM];
+       int     i;
+       int     pow;
+
+       game += ft_strlen("Card   1:");
+       i = 0;
+       while (i < WINNING_NUM)
+       {
+               winning[i++] = ft_atoi(game);
+               game += 3;
+       }
+       i = 0;
+       game += 2;
+       pow = 0;
+       while (i < NUMBERS_NUM)
+       {
+               pow += is_winning(ft_atoi(game), winning);
+               game += 3;
+               ++i;
+       }
+       return (pow);
+}
+
+void   apply_scores(t_record records[GAMES])
+{
+       int     i;
+       int     j;
+       int     copies;
+
+       i = 0;
+       while (i < GAMES)
+       {
+               j = records[i].score;
+               copies = records[i].copies;
+               while (j > 0)
+               {
+                       if (i + j < GAMES)
+                               records[i + j].copies += copies;
+                       --j;
+               }
+               ++i;
+       }
+       return ;
+}
+
+int    sum_copies(t_record records[GAMES])
+{
+       int     i;
+       int     result;
+
+       result = 0;
+       i = 0;
+       while (i < GAMES)
+       {
+               result += records[i].copies;
+               ++i;
+       }
+       return (result);
+}
+
+int main(int argc, char **argv)
+{
+       int                     result;
+       char            *game;
+       int                     fd;
+       t_record        records[GAMES];
+       int                     i;
+
+       if (argc != 2)
+               return (1);
+       fd = open(argv[1], O_RDONLY);
+       if (fd < 0)
+               return (2);
+       game = get_next_line(fd);
+       result = 0;
+       i = 0;
+       while (game)
+       {
+               records[i].score = score(game);
+               free(game);
+               records[i].copies = 1;
+               ++i;
+               game = get_next_line(fd);
+       }
+       apply_scores(records);
+       ft_printf("The resulting score is %i.\n", sum_copies(records));
+       return (0);
+}