Advertisement
mosredna

AoC 2023 day 10

Dec 10th, 2023 (edited)
991
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.73 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 = 0
  7. let part2 = 0
  8. let input = fs.readFileSync(__dirname + "/data.txt", "utf8").split(eol)
  9.  
  10. let pos
  11. let map = input.map((val, i) => {
  12.     let row = val.split("")
  13.     let sPos = row.indexOf("S")
  14.     if (sPos > -1) {
  15.         pos = { x: sPos, y: i }
  16.         row[sPos] = "J" // My startNode, might be different for other maps
  17.     }
  18.     return row
  19. })
  20.  
  21. const topN = "|JL"
  22. const leftN = "-7J"
  23. const bottomN = "|7F"
  24. const rightN = "-LF"
  25.  
  26. const visited = new Set()
  27.  
  28. function getNext(pos) {
  29.     let type = map[pos.y][pos.x]
  30.     if (topN.includes(type) && !visited.has(`${pos.x}-${pos.y - 1}`)) return { x: pos.x, y: pos.y - 1 }
  31.     if (leftN.includes(type) && !visited.has(`${pos.x - 1}-${pos.y}`)) return { x: pos.x - 1, y: pos.y }
  32.     if (bottomN.includes(type) && !visited.has(`${pos.x}-${pos.y + 1}`)) return { x: pos.x, y: pos.y + 1 }
  33.     if (rightN.includes(type) && !visited.has(`${pos.x + 1}-${pos.y}`)) return { x: pos.x + 1, y: pos.y }
  34. }
  35.  
  36. while (true) {
  37.     visited.add(`${pos.x}-${pos.y}`)
  38.     pos = getNext(pos)
  39.     if (pos == undefined) break
  40. }
  41.  
  42. part1 = visited.size / 2
  43.  
  44. function countCrossings(inputString) {
  45.     const matches = inputString.match(/\||L7|FJ/g)
  46.     return matches ? matches.length : 0
  47. }
  48.  
  49. map.forEach((row, y) => {
  50.     let rowM = ""
  51.     row.forEach((element, x) => {
  52.         let poly = visited.has(`${x}-${y}`)
  53.         if (poly && element != "-") rowM += element
  54.         if (!poly && countCrossings(rowM) & 1) part2++
  55.     })
  56. })
  57.  
  58. let endTime = performance.now() - startTime
  59. console.log(`Part 1: ${part1}\nPart 2: ${part2}\nTimer: ${endTime} ms`)
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement