Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
shahata committed Dec 16, 2024
1 parent 4db8ae2 commit 701ab1c
Showing 1 changed file with 12 additions and 13 deletions.
25 changes: 12 additions & 13 deletions src/2024/day16.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ function parse(input) {
return { map, start: { x, y, direction: "right" }, end: { x: ex, y: ey } };
}

function getNeighbors(current, map) {
function getNeighbors(map, current) {
const opposite = { up: "down", down: "up", left: "right", right: "left" };
let neighbors = [
{ x: current.x - 1, y: current.y, direction: "left" },
Expand All @@ -25,22 +25,22 @@ function getNeighbors(current, map) {
return neighbors;
}

function solve(input) {
export function solve(input) {
const key = p => `${p.x},${p.y},${p.direction}`;
let { map, start, end } = parse(input);
let curr = { ...start, score: 0, path: new Set([`${start.x},${start.y}`]) };
let queue = [curr];
let visited = new Map();
let results = [{ score: Infinity }];
const key = p => `${p.x},${p.y},${p.direction}`;
visited.set(key(curr), curr);
let visited = new Map([[key(curr), curr]]);
let score = Infinity;
let tiles;
while (queue.length > 0) {
curr = queue.shift();
if (curr.x === end.x && curr.y === end.y) {
if (curr.score < results[0].score) results = [curr];
if (curr.score === results[0].score) results.push(curr);
if (curr.score < score) tiles = curr.path.size;
score = Math.min(score, curr.score);
continue;
}
getNeighbors(curr, map).forEach(n => {
getNeighbors(map, curr).forEach(n => {
const prev = visited.get(key(n));
if (!prev || prev.score > n.score) {
queue.push(n);
Expand All @@ -50,14 +50,13 @@ function solve(input) {
}
});
}
return results;
return { score, tiles };
}

export function part1(input) {
return solve(input)[0].score;
return solve(input).score;
}

export function part2(input) {
const results = solve(input).map(result => result.path);
return results.reduce((acc, next) => acc.union(next)).size;
return solve(input).tiles;
}

0 comments on commit 701ab1c

Please sign in to comment.