mosredna

AoC 2024 day 10

Dec 10th, 2024 (edited)
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.82 KB | Source Code | 0 0
  1. const fs = require("fs")
  2.  
  3. const input = fs.readFileSync(__dirname + (process.argv.includes("--test") ? "/test.txt" : "/input.txt"), "utf8")
  4.  
  5. const map = input
  6.     .trim()
  7.     .split(/\r?\n/)
  8.     .map((row) => row.split("").map(Number))
  9.  
  10. const numRows = map.length
  11. const numCols = map[0].length
  12.  
  13. const directions = [
  14.     [0, 1],
  15.     [0, -1],
  16.     [1, 0],
  17.     [-1, 0]
  18. ]
  19.  
  20. const isValidMove = (map, x, y, currentHeight) =>
  21.     x >= 0 && x < map.length && y >= 0 && y < map[0].length && map[x][y] === currentHeight + 1
  22.  
  23. const traverse = (map, func) => {
  24.     let sum = 0
  25.     for (let i = 0; i < numRows; i++) {
  26.         for (let j = 0; j < numCols; j++) {
  27.             if (map[i][j] === 0) {
  28.                 sum += func(i, j)
  29.             }
  30.         }
  31.     }
  32.     return sum
  33. }
  34.  
  35. const findTrails = (x, y, visited) => {
  36.     visited ||= new Set()
  37.  
  38.     const key = `${x},${y}`
  39.     if (visited.has(key)) return 0
  40.     visited.add(key)
  41.  
  42.     if (map[x][y] === 9) return 1
  43.  
  44.     let score = 0
  45.     for (const [dx, dy] of directions) {
  46.         const newX = x + dx,
  47.             newY = y + dy
  48.         if (isValidMove(map, newX, newY, map[x][y]) && !visited.has(`${newX},${newY}`)) {
  49.             score += findTrails(newX, newY, visited)
  50.         }
  51.     }
  52.  
  53.     return score
  54. }
  55.  
  56. const countTrails = (x, y) => {
  57.     if (map[x][y] === 9) return 1
  58.  
  59.     let count = 0
  60.     for (const [dx, dy] of directions) {
  61.         const newX = x + dx,
  62.             newY = y + dy
  63.         if (isValidMove(map, newX, newY, map[x][y])) {
  64.             count += countTrails(newX, newY)
  65.         }
  66.     }
  67.  
  68.     return count
  69. }
  70.  
  71. console.time("Part 1 Time")
  72. console.log("Part 1:", traverse(map, findTrails))
  73. console.timeEnd("Part 1 Time")
  74.  
  75. console.time("Part 2 Time")
  76. console.log("Part 2:", traverse(map, countTrails))
  77. console.timeEnd("Part 2 Time")
  78.  
Advertisement
Add Comment
Please, Sign In to add comment