Day 6 part 2 complete! Plus a little cleanup in part 1. :)

This commit is contained in:
Alexander Andreev 2023-12-06 19:26:59 +04:00
parent e3fa47e071
commit 2ae96c9a04
Signed by: Arav
GPG Key ID: D22A817D95815393
3 changed files with 87 additions and 9 deletions

View File

@ -31,7 +31,7 @@ day5: day5/p1.c day5/p2.c
day6: day6/p1.c day6/p2.c
${CC} ${CFLAGS} $@/p1.c -o bin/$@p1
# ${CC} ${CFLAGS} $@/p2.c -o bin/$@p2
${CC} ${CFLAGS} $@/p2.c -o bin/$@p2
clean:
rm -f bin/day*p*

View File

@ -42,8 +42,7 @@ int main(int argc, char **argv) {
for (ssize_t i = time_line_length-2, j = 0;;) {
while (!ISDIGIT(time_line[i])) {
--i;
if (time_line[i] == ':')
if (time_line[--i] == ':')
goto tl_end;
}
@ -58,8 +57,7 @@ int main(int argc, char **argv) {
for (ssize_t i = distance_line_length-2, j = 0;;) {
while (!ISDIGIT(distance_line[i])) {
--i;
if (distance_line[i] == ':')
if (distance_line[--i] == ':')
goto dl_end;
}
@ -78,8 +76,6 @@ int main(int argc, char **argv) {
uint64_t tmid = times[i] / 2;
uint64_t ways = 0;
printf(":: %lu\n", times[i]);
for (uint64_t ht = tmid; ht <= times[i]; ++ht) {
if (ht * (times[i] - ht) > distances[i])
++ways;
@ -94,8 +90,6 @@ int main(int argc, char **argv) {
break;
}
printf(":: %lu = %lu\n", times[i], ways);
total_ways *= ways;
}

84
day6/p2.c Normal file
View File

@ -0,0 +1,84 @@
#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;
}