Advertisement
mosredna

AoC 2022 day 12

Dec 12th, 2022 (edited)
831
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 2.09 KB | Source Code | 0 0
  1. const fs = require('fs')
  2. const performance = require('perf_hooks').performance
  3. const eol = require('os').EOL
  4.  
  5. let startTime = performance.now()
  6. let part1 = part2 = Infinity
  7. let input = fs.readFileSync(__dirname + "/data.txt", 'utf8').split(eol)
  8.  
  9. const edges = [
  10.     [0, -1],
  11.     [0, 1],
  12.     [-1, 0],
  13.     [1, 0]
  14. ]
  15. let start, end
  16. // create a 2d array with all the nodes
  17. let map = input.map((row, y) => {
  18.     return row.split('').map((char, x) => {
  19.         let node = {
  20.             x,
  21.             y,
  22.             visited: false,
  23.             height: char.charCodeAt(0) - 96,
  24.             distance: Infinity,
  25.             edgeNodes: []
  26.         }
  27.         if (char == 'S')
  28.             node.height = 1, start = node
  29.         if (char == 'E')
  30.             node.height = 26, end = node
  31.         return node
  32.     })
  33. })
  34. // calculate all connected nodes per node
  35. map.forEach(r => {
  36.     r.forEach(node => {
  37.         edges.forEach(edge => {
  38.             if (map[node.y + edge[1]]) {
  39.                 let n = map[node.y + edge[1]][node.x + edge[0]]
  40.                 n && node.edgeNodes.push(n)
  41.             }
  42.         })
  43.     })
  44. })
  45. // calculate length of shortest path
  46. function solve(n) {
  47.     n.distance = 0
  48.     let queue = [n]
  49.     let solution = Array(2).fill(-1)
  50.     while (queue.length) {
  51.         let node = queue.shift()
  52.         for (const edge of node.edgeNodes) {
  53.             if (!edge.visited && (node.height - edge.height) < 2) {
  54.                 let distance = node.distance + 1
  55.                 if ((edge.x == 0 && edge.y == start.y && solution[0] == -1)) {
  56.                     solution[0] = distance
  57.                 } else if (edge.x == 0 && solution[1] == -1) {
  58.                     solution[1] = distance
  59.                 }
  60.                 edge.visited = true
  61.                 edge.distance = distance
  62.                 queue.push(edge)
  63.                 if (solution.indexOf(-1) == -1) return solution
  64.             }
  65.         }
  66.     }
  67.     return solution
  68. }
  69.  
  70. [part1, part2] = solve(end)
  71. let time = performance.now() - startTime
  72. console.log(`Part 1: ${part1}\nPart 2: ${part2}\nTimer: ${time} ms`)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement