AdventOfCode/2019/days/3/2/main.c

78 lines
1.9 KiB
C

#include <stdio.h>
#include <stdlib.h>
#define POINTLIMIT 500000
int main(void) {
signed int lines[2][POINTLIMIT][3];
unsigned int bufpos = 0, pp = 0, linep[2];
short line = 0, bufls = 0, res;
char numbuf[16], dir, c;
fprintf(stderr,"\e[1;31mParsing input...\n");
while ((c=getchar())!=EOF) {
if (c >= 'A' && c <= 'Z') {
dir = c;
} else if (c == ',' || c == '\n') {
numbuf[bufpos] = '\0';
for (int i = 0; i<atoi(numbuf); i++) {
int start = 0;
if (pp>1) {
start = pp-1;
}
lines[line][pp][0] = lines[line][start][0];
lines[line][pp][1] = lines[line][start][1];
lines[line][pp][2] = 0;
int va,val;
switch (dir) {
case 'U': va = 1, val=1; break;
case 'R': va = 0, val=1; break;
case 'D': va = 1, val=-1; break;
case 'L': va = 0, val=-1; break;
}
lines[line][pp][va] = lines[line][start][va]+val;
pp++;
}
if (c == '\n') {
linep[line]=pp-1;
line++;
pp = 0;
}
bufpos = 0, bufls = 0;
} else if (c >= '0' && c <= '9') {
numbuf[bufpos++] = c;
bufls = 1;
} else {
return 1;
}
}
fprintf(stderr,"Finding closest match...\n");
int num[3] = {0};
for (int x=0, m=0; x<linep[0] && x<POINTLIMIT; x++) {
for (int y=0; y<linep[1] && y<POINTLIMIT; y++) {
if (
lines[0][x][0] == lines[1][y][0] &&
lines[0][x][1] == lines[1][y][1]
) {
if (lines[0][x][0] < 0) {
num[1] = lines[0][x][0]*-1;
} else {
num[1] = lines[0][x][0];
}
if (lines[0][x][1] < 0) {
num[2] = lines[0][x][1]*-1;
} else {
num[2] = lines[0][x][1];
}
if (num[0] == 0 || num[0] > num[1] + num[2]) {
num[0] = num[1] + num[2];
}
fprintf(stderr,"\e[0mFound %i|%i and %i|%i!\n\e[1;31mFound %i match(es)...\r", lines[0][x][0], lines[0][x][1], lines[1][y][0], lines[1][y][1], ++m);
}
}
res = num[0];
}
fprintf(stderr,"\nBingo:\n");
printf("%i\n", res);
return 0;
}