Public
Edited
Dec 17, 2022
Insert cell
Insert cell
headMoves = parseInput(sampleInput)
Insert cell
Insert cell
tailPosition(head)
Insert cell
m = puzzleAnswer(sampleInput)
Insert cell
puzzleAnswer = (inputText) => {
const moves = parseInput(inputText);
const head = headPositions(0, 0, moves);
const tail = tailPosition(head).map((d) => `${d.x},${d.y}`);
return _.uniq(tail);
}
Insert cell
Insert cell
sign = (value) => value / Math.abs(value)
Insert cell
Insert cell
function headPositions(x, y, moves) {
return moves.reduce((acc, move) => {
if (acc.length === 0) {
return [{ x, y }];
}

const curr = _.last(acc);
const next = nextPosition(curr.x, curr.y, move);
return [...acc, next];
}, []);
}
Insert cell
function nextPosition(x, y, move) {
if (move.dir === "R") {
return { x: x + 1, y };
}
if (move.dir === "L") {
return { x: x - 1, y };
}
if (move.dir === "U") {
return { x, y: y - 1 };
}
if (move.dir === "D") {
return { x, y: y + 1 };
}
}
Insert cell
function parseInput(inputText) {
return inputText
.split(NEWLINE)
.map((line) => line.split(SPACE))
.map(([dir, steps]) => ({ dir, steps: +steps }))
.flatMap(({ dir, steps }) => repeat({ dir, steps: 1 }, steps));
}
Insert cell
Insert cell
import { NEWLINE, SPACE } from "@pnavarrc/advent-of-code-utils"
Insert cell
Insert cell
Insert cell
puzzleInput = FileAttachment("2022-09-puzzle-input.txt").text()
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more