adventofcode/2022/09/part1.js

71 lines
1.5 KiB
JavaScript

import * as R from "remeda";
import Victor from "@a-robu/victor";
import { readFile } from "../05/part1.js";
import { passthru } from '../08/part1.js'
const directions = {
R: new Victor(1,0),
L: new Victor(-1,0),
U: new Victor(0,1),
D: new Victor(0,-1),
}
const parseLine = R.createPipe(
line => line.split(" "),
([direction,times]) => Array(parseInt(times)).fill(directions[direction])
);
const readInput = (...args) => R.pipe(
readFile(...args),
text => text.split("\n"),
R.compact,
R.map( parseLine ),
R.flatten,
)
export const puzzleInput = readInput(import.meta.url, "input");
export const sample = readInput(import.meta.url, "sample");
const touching = (v1,v2) => [v1.distanceX(v2), v1.distanceY(v2)].every(
x => x*x <= 1
);
export function moveOnce( head, tail, d ) {
head.add(d);
if( touching(head,tail) ) return;
const delta = head.clone().subtract(tail).normalize();
if( delta.x * delta.y ) {
delta.x = delta.x > 0 ? 1 : -1;
delta.y = delta.y > 0 ? 1 : -1;
}
tail.add(delta);
}
const moveAround = (directives) => {
const head = new Victor(0,0);
const tail = new Victor(0,0);
const visited = [ tail.toString() ]
for ( const d of directives ) {
moveOnce(head,tail,d);
visited.push( tail.toString() );
}
return visited;
};
export default R.createPipe(
moveAround,
passthru( x => console.log(x) ),
R.uniq,
R.countBy( R.identity )
);