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

diff --git a/6/6.c b/6/6.c
new file mode 100644 (file)
index 0000000..e626761
--- /dev/null
+++ b/6/6.c
@@ -0,0 +1,77 @@
+
+#include <stdlib.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <math.h>
+#include "libft.h"
+
+int    special_is_whole(int time, int record)
+{
+       int     n;
+
+       n = 1;
+       while (n <= time / 2)
+       {
+               if (record == n * (time - n))
+                       return (1);
+               ++n;
+       }
+       return (0);
+}
+
+int    ways_of_winning(int time, int record)
+{
+       double  special;
+       int             correction;
+
+       correction = 0;
+       special = sqrt(time * time / 4. - record);
+       if (isnan(special))
+               return (0);
+       if (special_is_whole(time, record))
+       {
+               if (special < 1)
+                       return (0);
+               correction = 2;
+       }
+       if (time % 2 == 0)
+               return (2 * floor(special) + 1 - correction);
+       if (fmod(special, 1.) < 0.5)
+               return (2 * floor(special) - correction);
+       return (2 * floor(special) + 2 - correction);
+}
+
+int    main(int argc, char **argv)
+{
+       int             fd;
+       int             result;
+       char    *times;
+       char    *records;
+       size_t  t;
+       size_t  r;
+
+       fd = open(argv[1], O_RDONLY);
+       times = get_next_line(fd);
+       records = get_next_line(fd);
+       t = 0;
+       r = 0;
+       result = 1;
+       while (times[t] != '\n' && records[r] != '\n')
+       {
+               while (!ft_isdigit(times[t]))
+                       ++t;
+               while (!ft_isdigit(records[r]))
+                       ++r;
+               result *= ways_of_winning(ft_atoi(times + t), ft_atoi(records + r));
+               while (ft_isdigit(times[t]))
+                       ++t;
+               while (ft_isdigit(records[r]))
+                       ++r;
+       }
+       ft_printf("The resulting product is %i.\n", result);
+       get_next_line(fd);
+       close(fd);
+       free(times);
+       free(records);
+       return (0);
+}