Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Advent of Code 2024 - Day 6
- const fs = require("fs")
- const input = fs.readFileSync(__dirname + (process.argv.includes("--test") ? "/test.txt" : "/input.txt"), "utf8")
- const parseInput = (rawInput) => {
- return rawInput.split(/\r?\n/).map((r) => r.split(""))
- }
- const directions = [
- [-1, 0], // up
- [0, 1], // right
- [1, 0], // down
- [0, -1] // left
- ]
- function findStartPosition(map) {
- for (let i = 0; i < map.length; i++) {
- const col = map[i].indexOf("^")
- if (col !== -1) return [i, col] // Return the position as soon as we find '^'
- }
- }
- const visitedPositions = new Set()
- const part1 = (map) => {
- let guardPos = [...guardStartPos]
- let directionIndex = 0
- const rows = map.length
- const cols = map[0].length
- while (true) {
- const [dx, dy] = directions[directionIndex]
- const [x, y] = guardPos
- const nextPos = [x + dx, y + dy]
- if (nextPos[0] < 0 || nextPos[0] >= rows || nextPos[1] < 0 || nextPos[1] >= cols) {
- break
- }
- if (map[nextPos[0]][nextPos[1]] !== "#") {
- visitedPositions.add(nextPos.toString())
- guardPos = nextPos
- } else {
- directionIndex = (directionIndex + 1) % directions.length
- }
- }
- return visitedPositions.size
- }
- const part2 = (map) => {
- const rows = map.length
- const cols = map[0].length
- const simulateMovement = (modifiedMap) => {
- const visitedStates = new Set()
- let guardPos = [...guardStartPos]
- let directionIndex = 0
- while (true) {
- const [dx, dy] = directions[directionIndex]
- const [x, y] = guardPos
- const nextPos = [x + dx, y + dy]
- if (nextPos[0] < 0 || nextPos[0] >= rows || nextPos[1] < 0 || nextPos[1] >= cols) {
- return false
- }
- if (modifiedMap[nextPos[0]][nextPos[1]] !== "#") {
- const stateKey = `${guardPos}-${directionIndex}`
- if (visitedStates.has(stateKey)) {
- return true
- }
- visitedStates.add(stateKey)
- guardPos = nextPos
- } else {
- directionIndex = (directionIndex + 1) % directions.length
- }
- }
- }
- let loopCount = 0
- visitedPositions.delete(guardStartPos.toString())
- for (const pos of visitedPositions) {
- const [row, col] = pos.split(",").map(Number)
- const modifiedMap = map.map((row) => [...row])
- modifiedMap[row][col] = "#"
- if (simulateMovement(modifiedMap)) {
- loopCount++
- }
- }
- return loopCount
- }
- const data = parseInput(input)
- let guardStartPos = findStartPosition(data)
- console.time("Part 1 Time")
- console.log("Part 1:", part1(data))
- console.timeEnd("Part 1 Time")
- console.time("Part 2 Time")
- console.log("Part 2:", part2(data))
- console.timeEnd("Part 2 Time")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement