aoc2023/day6/p2.c

84 lines
2.0 KiB
C
Raw Normal View History

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#define ISDIGIT(c) (c >= 0x30 && c <= 0x39)
int main(int argc, char **argv) {
FILE *input;
size_t line_buf_length = 0;
if (argc == 1 || argv[1][0] == '-')
input = stdin;
else if ((input = fopen(argv[1], "r")) == NULL) {
fprintf(stderr, "Cannot open file %s\n", argv[1]);
return -1;
}
char *time_line = NULL, *distance_line = NULL;
ssize_t time_line_length = 0, distance_line_length = 0;
if ((time_line_length = getline(&time_line, &line_buf_length, input)) == -1) {
fprintf(stderr, "No time line in a file %s.", argv[1]);
return -1;
}
if ((distance_line_length = getline(&distance_line, &line_buf_length, input)) == -1) {
fprintf(stderr, "No distance line in a file %s.", argv[1]);
return -1;
}
uint64_t time = 0, distance = 0;
for (ssize_t i = time_line_length-2, m = 1;; --i) {
while (!ISDIGIT(time_line[i])) {
if (time_line[--i] == ':')
goto tl_end;
}
while (ISDIGIT(time_line[i])) {
time += (time_line[i--]&0xf) * m;
m *= 10;
}
}
tl_end:
for (ssize_t i = distance_line_length-2, m = 1;; --i) {
while (!ISDIGIT(distance_line[i])) {
if (distance_line[--i] == ':')
goto dl_end;
}
while (ISDIGIT(distance_line[i])) {
distance += (distance_line[i--]&0xf) * m;
m *= 10;
}
}
dl_end:
uint64_t total_ways = 0;
uint64_t tmid = time / 2;
for (uint64_t ht = tmid; ht <= time; ++ht) {
if (ht * (time - ht) > distance)
++total_ways;
else
break;
}
for (uint64_t ht = tmid-1; ht != 0; --ht) {
if (ht * (time - ht) > distance)
++total_ways;
else
break;
}
printf("%lu\n", total_ways);
return 0;
}