From 4dd516d9dc34c25eddaa712c47424b34cd7e6cdf Mon Sep 17 00:00:00 2001 From: Chris Date: Mon, 16 Dec 2024 22:23:04 +0000 Subject: [PATCH] Day 16 --- 2024/16/index.ts | 33 +++++++++++++++++++++------------ 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/2024/16/index.ts b/2024/16/index.ts index 0901d12..526ef1e 100644 --- a/2024/16/index.ts +++ b/2024/16/index.ts @@ -91,7 +91,6 @@ function fillDeadEnd(pos: Coord): void { }; } -printMap(); for (let y = 1; y < height - 1; y++) { for (let x = 1; x < width - 1; x++) { const pos = { x, y }; @@ -104,29 +103,30 @@ for (let y = 1; y < height - 1; y++) { } } } -printMap(); let fastest: number|null = null; const scoreCache: { [key: string]: [number, Coord, Dir] } = {}; -const scores: Array = []; +const branchCache: { [key: string]: number } = {}; + +const scores: Array<[number, Array]> = []; function getScoresAfterPosition(pos: Coord, dir: Dir, currentScore = 0, path: Array = [], lastBranch: [number, Coord]|null = null): void { if (fastest !== null && currentScore >= fastest) { return; } - const cache = scoreCache[`${pos.x},${pos.y}`]; - if (cache) { - currentScore += cache[0]; - pos = cache[1]; - dir = cache[2]; - } const branch = isBranch(pos, dir); if (branch) { + const cacheKey = `${pos.x},${pos.y},${dir}`; + const cache = branchCache[cacheKey]; + if (cache && cache < currentScore) { + return; + } else { + branchCache[cacheKey] = currentScore; + } if (lastBranch) { scoreCache[`${lastBranch[1].x},${lastBranch[1].y}`] = [currentScore - lastBranch[0], pos, dir]; - console.log(scoreCache); } lastBranch = [currentScore, pos]; } @@ -142,7 +142,7 @@ function getScoresAfterPosition(pos: Coord, dir: Dir, currentScore = 0, path: Ar fastest = score; } lastBranch = null; - scores.push(score); + scores.push([score, [...path, nextStr]]); return; } else if (nextChar === '.') { getScoresAfterPosition(next, newDir, score, [...path, nextStr], branch ? [score, next] : lastBranch); @@ -155,4 +155,13 @@ function getScoresAfterPosition(pos: Coord, dir: Dir, currentScore = 0, path: Ar getScoresAfterPosition(snakePos, snakeDir); -console.log(Math.min(...scores)); \ No newline at end of file +const fastestScore = Math.min(...scores.map(([score]) => score)); + +let coordsOnPaths: Set = new Set(); +scores.forEach(([score, path]) => { + if (score === fastestScore) { + path.forEach((coord) => coordsOnPaths.add(coord)); + } +}); + +console.log(coordsOnPaths.size + 1);