Skip to content

Instantly share code, notes, and snippets.

@MJGTwo
Last active December 3, 2019 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MJGTwo/4ecf026e65c4da0da627ddddd66daa53 to your computer and use it in GitHub Desktop.
Save MJGTwo/4ecf026e65c4da0da627ddddd66daa53 to your computer and use it in GitHub Desktop.
i1 = "R8,U5,L5,D3";
i2 = "U7,R6,D4,L4";
const dx = { L: -1, R: 1, U: 0, D: 0 };
const dy = { U: -1, D: 1, R: 0, L: 0 };
const parse = steps => steps.split(",");
const toString = pos => `${pos[0]},${pos[1]}`;
wire1 = parse(i1);
wire2 = parse(i2);
length = 0;
x = 0;
y = 0;
const points = wire =>
wire
.map(step => move(step[0], +step.slice(1)))
.reduce((allPoints, points) => ({ ...allPoints, ...points }));
const move = (direction, distance) =>
Array.from(Array(distance).keys()).reduce((answer, step) => {
x += dx[direction];
y += dy[direction];
length++;
key = toString([x, y]);
answer[key] ? null : (answer[key] = length);
return answer;
}, {});
const intersect = (w1, w2) => w1.filter(el => w2.includes(el));
const manhattenDist = point => Math.abs(+point[0]) + Math.abs(+point[1]);
const p1 = wires => Math.min(...wires.map(parse).map(manhattenDist));
const p2 = (wires, w1, w2) =>
Math.min(...wires.map(point => w1[point] + w2[point]));
points1 = points(wire1);
length = 0;
x = 0;
y = 0;
points2 = points(wire2);
wires12 = intersect(Object.keys(points1), Object.keys(points2));
console.log(p1(wires12));
console.log(p2(wires12, points1, points2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment