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

diff --git a/6/6b.c b/6/6b.c
new file mode 100644 (file)
index 0000000..a44e134
--- /dev/null
+++ b/6/6b.c
@@ -0,0 +1,80 @@
+
+#include <stdlib.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <math.h>
+#include "libft.h"
+
+int    special_is_whole(long time, long record)
+{
+       long    n;
+
+       n = 1;
+       while (n <= time / 2)
+       {
+               if (record == n * (time - n))
+                       return (1);
+               ++n;
+       }
+       return (0);
+}
+
+long   ways_of_winning(long time, long record)
+{
+       double          special;
+       long            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);
+}
+
+void   rearrange(char *str)
+{
+       size_t  new;
+       size_t  old;
+
+       new = 0;
+       old = 0;
+       while (str[old])
+       {
+               if (ft_isdigit(str[old]))
+                       str[new++] = str[old];
+               ++old;
+       }
+       str[new] = '\0';
+       return ;
+}
+
+int    main(int argc, char **argv)
+{
+       int             fd;
+       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);
+       rearrange(times);
+       rearrange(records);
+       ft_printf("There is %i ways to win this.\n", ways_of_winning(ft_atol(times), ft_atol(records)));
+       get_next_line(fd);
+       close(fd);
+       free(times);
+       free(records);
+       return (0);
+}