adventofcode/2022/09/part1.js

60 lines
1.3 KiB
JavaScript
Raw Normal View History

2022-12-09 17:28:05 +00:00
import * as R from "remeda";
import Victor from "@a-robu/victor";
import { readFile } from "../05/part1.js";
2022-12-09 18:05:42 +00:00
import { passthru } from "../08/part1.js";
2022-12-09 17:28:05 +00:00
const directions = {
2022-12-09 18:05:42 +00:00
R: new Victor(1, 0),
L: new Victor(-1, 0),
U: new Victor(0, 1),
D: new Victor(0, -1),
};
2022-12-09 17:28:05 +00:00
const parseLine = R.createPipe(
2022-12-09 18:05:42 +00:00
(line) => line.split(" "),
([direction, times]) => Array(parseInt(times)).fill(directions[direction])
2022-12-09 17:28:05 +00:00
);
2022-12-09 18:05:42 +00:00
export const readInput = (...args) =>
R.pipe(
readFile(...args),
(text) => text.split("\n"),
R.compact,
R.map(parseLine),
R.flatten
);
2022-12-09 17:28:05 +00:00
export const puzzleInput = readInput(import.meta.url, "input");
export const sample = readInput(import.meta.url, "sample");
2022-12-09 18:05:42 +00:00
export const touching = (v1, v2) =>
[v1.distanceX(v2), v1.distanceY(v2)].every((x) => x * x <= 1);
2022-12-09 17:28:05 +00:00
2022-12-09 18:05:42 +00:00
export const moveOnce = (head, tail) => (d) => {
head.add(d);
2022-12-09 17:28:05 +00:00
2022-12-09 18:05:42 +00:00
if (touching(head, tail)) return tail.toString();
2022-12-09 17:28:05 +00:00
2022-12-09 18:05:42 +00:00
const delta = head.clone().subtract(tail).normalize();
2022-12-09 17:28:05 +00:00
2022-12-09 18:05:42 +00:00
if (delta.x * delta.y) {
delta.x = delta.x > 0 ? 1 : -1;
delta.y = delta.y > 0 ? 1 : -1;
}
2022-12-09 17:28:05 +00:00
2022-12-09 18:05:42 +00:00
tail.add(delta);
2022-12-09 17:33:37 +00:00
2022-12-09 18:05:42 +00:00
return tail.toString();
};
2022-12-09 17:28:05 +00:00
const moveAround = (directives) => {
2022-12-09 18:05:42 +00:00
const head = new Victor(0, 0);
const tail = new Victor(0, 0);
2022-12-09 17:28:05 +00:00
2022-12-09 18:05:42 +00:00
const move = moveOnce(head, tail);
return directives.map(move);
2022-12-09 17:28:05 +00:00
};
2022-12-09 18:05:42 +00:00
export default R.createPipe(moveAround, R.uniq, (moves) => moves.length);