advent2019

Advent of Code 2019 (C99)
git clone git://bsandro.tech/advent2019
Log | Files | Refs | LICENSE

commit a15787646c702afe8d9f9808d2c943992e1f7c36
parent 9d237f29e03cd4ecb44b1760d5edc0f39bcb496d
Author: bsandro <email@bsandro.tech>
Date:   Fri, 26 Dec 2025 00:43:14 +0200

day03 p1

Diffstat:
Aday03.c | 113+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 113 insertions(+), 0 deletions(-)

diff --git a/day03.c b/day03.c @@ -0,0 +1,113 @@ +#include <stdio.h> +#include <inttypes.h> +#include <stdbool.h> +#include <stdlib.h> +#include "cputime.h" + +typedef struct { + char data[8]; + int len; +} Buffer; + +typedef struct { + int x, y; +} Vec2; + +typedef struct { + Vec2 p1, p2; +} Line; + +typedef struct { + int len; + Line lines[512]; +} Wire; + +int btoi(Buffer buf) { + int num = 0; + for (int i=0;i<buf.len;++i) num = num*10+buf.data[i]; + return num; +} + +Line normalize(Line l) { + if (l.p1.x>l.p2.x || l.p1.y>l.p2.y) { + Vec2 t = l.p1; + l.p1 = l.p2; + l.p2 = t; + } + return l; +} + +bool get_intersection(Line * restrict l1, Line * restrict l2, Vec2 * restrict p) { + (void)p; + if (l1->p1.x==l1->p2.x) { // l1 vertical + if (l2->p1.x==l2->p2.x) return false; // l2 is vertical too + if (l1->p1.x>l2->p1.x && l1->p2.x<l2->p2.x && + l2->p1.y>l1->p1.y && l2->p2.y<l1->p2.y) { + p->x = l1->p1.x; + p->y = l2->p1.y; + return true; + } + } else if (l1->p1.y==l1->p2.y) { // l1 horizontal + if (l2->p1.y==l2->p2.y) return false; // l2 is horizontal too + if (l2->p1.x>l1->p1.x && l2->p2.x<l1->p2.x && + l1->p1.y>l2->p1.y && l1->p2.y<l2->p2.y) { + p->x = l2->p1.x; + p->y = l1->p1.y; + return true; + } + } + return false; +} + +int64_t calc_p1(Wire *w1, Wire *w2) { + int64_t r = -1; + for (int i=0;i<w1->len;++i) { + for (int j=0;j<w2->len;++j) { + Vec2 p = {0}; + if (get_intersection(&w1->lines[i], &w2->lines[j], &p)) { + int dist = abs(p.x)+abs(p.y); + printf("intersection: {%d,%d}, dist: %d\n", p.x, p.y, dist); + if (r==-1) r = dist; + else if (dist<r) r = dist; + } + } + } + return r; +} +// 369 too low +// 1167 too high +int main(void) { + Buffer buf = {0}; + Vec2 prev = {0}; + Wire w1 = {0}; + Wire w2 = {0}; + Wire *cw = &w1; + char dir; + for (int c=getchar();c!=EOF;c=getchar()) { + if (c==','||c=='\n') { + int dist = btoi(buf); + buf.len = 0; + Vec2 p = prev; + if (dir=='U') p.y += dist; + else if (dir=='D') p.y -= dist; + else if (dir=='L') p.x -= dist; + else if (dir=='R') p.x += dist; + cw->lines[cw->len++] = normalize((Line){ .p1=prev, .p2=p }); + prev = p; + if (c=='\n') { + cw = &w2; + prev.x = 0; + prev.y = 0; + } + } else if (c>='A'&&c<='Z') { + dir = c; + } else { + buf.data[buf.len++] = c-'0'; + } + } + int64_t p1 = calc_p1(&w1, &w2); + int64_t p2 = 0; + printf("p1: %"PRIi64"\np2: %"PRIi64"\n", p1, p2); + + return 0; +}