summary refs log tree commit diff homepage
diff options
context:
space:
mode:
authorJune McEnroe <june@causal.agency>2018-12-14 00:47:34 -0500
committerJune McEnroe <june@causal.agency>2020-11-22 00:14:25 -0500
commit75b51d8fc85c70d17c73e2d9958a57f908c0543e (patch)
tree700cc06f35611f29bc690457bfbc72868dfa4572
parentSolve day 14 part 1 (diff)
downloadaoc-75b51d8fc85c70d17c73e2d9958a57f908c0543e.tar.gz
aoc-75b51d8fc85c70d17c73e2d9958a57f908c0543e.zip
Solve day 14 part 2
-rw-r--r--2018/day14.c46
1 files changed, 27 insertions, 19 deletions
diff --git a/2018/day14.c b/2018/day14.c
index 9df7190..9d2bdd9 100644
--- a/2018/day14.c
+++ b/2018/day14.c
@@ -1,18 +1,17 @@
 #include <stdio.h>
 #include <stdlib.h>
-
-typedef unsigned uint;
+#include <string.h>
 
 struct Vec {
 	size_t cap, len;
-	uint *ptr;
+	char *ptr;
 };
 static struct Vec new(size_t cap) {
 	struct Vec vec = { cap };
 	vec.ptr = malloc(sizeof(*vec.ptr) * cap);
 	return vec;
 }
-static void push(struct Vec *vec, uint val) {
+static void push(struct Vec *vec, char val) {
 	if (vec->len == vec->cap) {
 		vec->cap *= 2;
 		vec->ptr = realloc(vec->ptr, sizeof(*vec->ptr) * vec->cap);
@@ -21,24 +20,33 @@ static void push(struct Vec *vec, uint val) {
 }
 
 int main() {
-	uint count;
-	scanf("%u", &count);
+	size_t count;
+	scanf("%zu", &count);
+	char *scores;
+	asprintf(&scores, "%zu", count);
 
 	struct Vec vec = new(256);
-	push(&vec, 3);
-	push(&vec, 7);
+	push(&vec, '3');
+	push(&vec, '7');
 
 	size_t elf[2] = { 0, 1 };
-	for (uint i = 0; i < count + 10; ++i) {
-		uint sum = vec.ptr[elf[0]] + vec.ptr[elf[1]];
-		if (sum / 10) push(&vec, sum / 10);
-		push(&vec, sum % 10);
-		elf[0] = (elf[0] + 1 + vec.ptr[elf[0]]) % vec.len;
-		elf[1] = (elf[1] + 1 + vec.ptr[elf[1]]) % vec.len;
-	}
-
-	for (uint i = count; i < count + 10; ++i) {
-		printf("%u", vec.ptr[i]);
+	for (size_t i = 0; 1; ++i) {
+		if (i == count + 10) {
+			for (size_t j = count; j < count + 10; ++j) {
+				printf("%c", vec.ptr[j]);
+			}
+			printf("\n");
+		}
+		char sum = (vec.ptr[elf[0]] - '0') + (vec.ptr[elf[1]] - '0');
+		if (sum / 10) push(&vec, '0' + sum / 10);
+		push(&vec, '0' + sum % 10);
+		elf[0] = (elf[0] + 1 + vec.ptr[elf[0]] - '0') % vec.len;
+		elf[1] = (elf[1] + 1 + vec.ptr[elf[1]] - '0') % vec.len;
+		size_t len = strlen(scores);
+		if (vec.len < len) continue;
+		char *match = strnstr(&vec.ptr[vec.len - len - 1], scores, len + 1);
+		if (!match) continue;
+		printf("%zu\n", match - vec.ptr);
+		break;
 	}
-	printf("\n");
 }