Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const fs = require("fs")
- const input = fs.readFileSync(__dirname + (process.argv.includes("--test") ? "/test.txt" : "/input.txt"), "utf8")
- const map = input
- .trim()
- .split(/\r?\n/)
- .map((row) => row.split("").map(Number))
- const numRows = map.length
- const numCols = map[0].length
- const directions = [
- [0, 1],
- [0, -1],
- [1, 0],
- [-1, 0]
- ]
- const isValidMove = (map, x, y, currentHeight) =>
- x >= 0 && x < map.length && y >= 0 && y < map[0].length && map[x][y] === currentHeight + 1
- const traverse = (map, func) => {
- let sum = 0
- for (let i = 0; i < numRows; i++) {
- for (let j = 0; j < numCols; j++) {
- if (map[i][j] === 0) {
- sum += func(i, j)
- }
- }
- }
- return sum
- }
- const findTrails = (x, y, visited) => {
- visited ||= new Set()
- const key = `${x},${y}`
- if (visited.has(key)) return 0
- visited.add(key)
- if (map[x][y] === 9) return 1
- let score = 0
- for (const [dx, dy] of directions) {
- const newX = x + dx,
- newY = y + dy
- if (isValidMove(map, newX, newY, map[x][y]) && !visited.has(`${newX},${newY}`)) {
- score += findTrails(newX, newY, visited)
- }
- }
- return score
- }
- const countTrails = (x, y) => {
- if (map[x][y] === 9) return 1
- let count = 0
- for (const [dx, dy] of directions) {
- const newX = x + dx,
- newY = y + dy
- if (isValidMove(map, newX, newY, map[x][y])) {
- count += countTrails(newX, newY)
- }
- }
- return count
- }
- console.time("Part 1 Time")
- console.log("Part 1:", traverse(map, findTrails))
- console.timeEnd("Part 1 Time")
- console.time("Part 2 Time")
- console.log("Part 2:", traverse(map, countTrails))
- console.timeEnd("Part 2 Time")
Advertisement
Add Comment
Please, Sign In to add comment