Skip to content

Commit

Permalink
feat(js): add solutions for 2024 day 18
Browse files Browse the repository at this point in the history
  • Loading branch information
timkurvers committed Dec 18, 2024
1 parent 70141f8 commit 531a486
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
52 changes: 52 additions & 0 deletions js/src/2024/18/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { Grid, astar, bisect, solution } from '../../utils/index.js';

const EMPTY = '.';
const CORRUPTED = '#';

const isEmpty = (point) => point.value === EMPTY;

const parse = (input) =>
input
.trim()
.split('\n')
.map((line) => line.split(',').map(Number));

const simulate = (bytes, size) => {
const memspace = new Grid();
memspace.fill(0, 0, size, size, EMPTY);
for (const [x, y] of bytes) {
memspace.set(x, y, CORRUPTED);
}
return memspace;
};

const speedrun = (memspace, size) => {
const start = memspace.getPoint(0, 0);
const goal = memspace.getPoint(size, size);

return astar(start, goal, {
neighborsFor: (current) => current.adjacentNeighbors.filter(isEmpty),
});
};

export const partOne = solution((input, { size = 70, numBytes = 1024 }) => {
const bytes = parse(input).slice(0, numBytes);
const memspace = simulate(bytes, size);
return speedrun(memspace, size).score;
});

export const partTwo = solution(async (input, { size = 70 }) => {
const bytes = parse(input);

const result = await bisect({
lower: 1,
upper: bytes.length,
until: (index) => {
const memspace = simulate(bytes.slice(0, index), size);
const candidate = speedrun(memspace, size);
return !candidate;
},
});

return bytes[result - 1].join(',');
});
37 changes: 37 additions & 0 deletions puzzles/2024/18/examples.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
part-one:
- input: &example1 |
5,4
4,2
4,5
3,0
2,1
6,3
2,4
1,5
0,6
3,3
2,6
5,1
1,2
5,5
2,5
6,5
1,4
0,4
6,4
1,1
6,1
1,0
0,5
1,6
2,0
answer: 22
args:
size: 6
num-bytes: 12

part-two:
- input: *example1
answer: 6,1
args:
size: 6

0 comments on commit 531a486

Please sign in to comment.