Skip to content

Commit

Permalink
feat(rust): add solution for 2024 day 16 part 1
Browse files Browse the repository at this point in the history
  • Loading branch information
timkurvers committed Dec 18, 2024
1 parent 95e6642 commit 0fc9661
Show file tree
Hide file tree
Showing 2 changed files with 98 additions and 0 deletions.
53 changes: 53 additions & 0 deletions js/src/2024/16/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import {
Cache,
Grid,
Orientation,
Rotation,
astar,
dx,
dy,
normalizeOrientation,
solution,
} from '../../utils/index.js';

const isWall = (point) => point.value === '#';

const parse = (input) => {
const maze = Grid.from(input);
const start = maze.find((point) => point.value === 'S');
const end = maze.find((point) => point.value === 'E');
return { maze, start, end };
};

const speedrun = ({ maze, start, end }) => {
const initial = { point: start, facing: Orientation.EAST };

const hash = (entry) => `${entry.point.label}:${entry.facing}`;
const cache = new Cache({ hash });

const best = astar(initial, null, {
cost: (from, to) => (from.point === to.point ? 1000 : 1),
done: (current) => current.point === end,
nodesFor: ({ point, facing }) => {
const nodes = [
cache.lookup({ point, facing: normalizeOrientation(facing + Rotation.TURN_RIGHT) }),
cache.lookup({ point, facing: normalizeOrientation(facing + Rotation.TURN_LEFT) }),
];

const forwards = maze.getPoint(point.x + dx(facing), point.y + dy(facing));
if (forwards && !isWall(forwards)) {
nodes.push(cache.lookup({ point: forwards, facing }));
}
return nodes;
},
});

return best;
};

export const partOne = solution((input) => {
const { maze, start, end } = parse(input);
return speedrun({ method: astar, maze, start, end }).score;
});

// TODO: Part two requires signficant changes to generic bfs implementation: later ;)
45 changes: 45 additions & 0 deletions puzzles/2024/16/examples.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
part-one:
- input: &example1 |
###############
#.......#....E#
#.#.###.#.###.#
#.....#.#...#.#
#.###.#####.#.#
#.#.#.......#.#
#.#.#####.###.#
#...........#.#
###.#.#####.#.#
#...#.....#.#.#
#.#.#.###.#.#.#
#.....#...#.#.#
#.###.#.#.#.#.#
#S..#.....#...#
###############
answer: 7036

- input: &example2 |
#################
#...#...#...#..E#
#.#.#.#.#.#.#.#.#
#.#.#.#...#...#.#
#.#.#.#.###.#.#.#
#...#.#.#.....#.#
#.#.#.#.#.#####.#
#.#...#.#.#.....#
#.#.#####.#.###.#
#.#.#.......#...#
#.#.###.#####.###
#.#.#...#.....#.#
#.#.#.#####.###.#
#.#.#.........#.#
#.#.#.#########.#
#S#.............#
#################
answer: 11048

part-two:
- input: *example1
answer: 45

- input: *example2
answer: 64

0 comments on commit 0fc9661

Please sign in to comment.