-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(js): add solutions for 2024 day 18
- Loading branch information
1 parent
70141f8
commit 531a486
Showing
2 changed files
with
89 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(','); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |