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

diff --git a/4/4.c b/4/4.c
new file mode 100644 (file)
index 0000000..697784e
--- /dev/null
+++ b/4/4.c
@@ -0,0 +1,83 @@
+
+#include <stdlib.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include "libft.h"
+
+#define WINNING_NUM 10
+#define NUMBERS_NUM 25
+
+int    power(int base, int pow)
+{
+       if (base == 0 || base == 1)
+               return (base);
+       if (pow < 0)
+               return (0);
+       if (pow == 0)
+               return (1);
+       if (pow == 1)
+               return (base);
+       if (pow % 2)
+               return (power(base * base, pow / 2) * base);
+       return (power(base * base, pow / 2));
+}
+
+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 = -1;
+       while (i < NUMBERS_NUM)
+       {
+               pow += is_winning(ft_atoi(game), winning);
+               game += 3;
+               ++i;
+       }
+       return (power(2, pow));
+}
+
+int main(int argc, char **argv)
+{
+       int             result;
+       char    *game;
+       int             fd;
+
+       if (argc != 2)
+               return (1);
+       fd = open(argv[1], O_RDONLY);
+       if (fd < 0)
+               return (2);
+       game = get_next_line(fd);
+       result = 0;
+       while (game)
+       {
+               result += score(game);
+               free(game);
+               game = get_next_line(fd);
+       }
+       ft_printf("The resulting score is %i.\n", result);
+       return (0);
+}