Files
advent-of-code/2023/day03/index.js
2024-12-16 22:21:16 +01:00

63 lines
2.2 KiB
JavaScript

import fs from 'node:fs'
const data = fs.readFileSync('input.txt', { encoding: "utf-8" }, data => data)
const filter_struct = /[^0-9.\n]/gms
const filter_data = /\d+/gms
const structureMap = []
const filtered_elements = [...data.matchAll(filter_struct)]
const lines = data.split('\n')
let res = 0
// --- filling array with unknown characters
for (let y = 0; y < lines.length; y++) {
const found_struct = [...lines[y].matchAll(filter_struct)]
found_struct.forEach(struct => {
structureMap.push({ name: struct[0], x: struct.index, y: y })
})
}
for (let y = 0; y < lines.length; y++) {
const found_numbers = [...lines[y].matchAll(filter_data)]
found_numbers.forEach(number => {
let result = false
console.log(`-------- ${number[0]}`)
result = isStructAroundMe(lines, { line: lines[y], y: y, x: number.index, xEnd: number.index + number[0].length - 1 })
if (result) res += parseInt(number[0])
if (!result) console.log(`
${number[0]} has no adjacent parts!
`)
})
}
console.log(structureMap)
console.log(res)
function findStructure(lines, x, y) {
if (!lines) return false
let result = structureMap.find(coords => coords.x === x && coords.y === y) ? true : false
return result
}
function isStructAroundMe(lines, pos) {
let result = false
const directions = [...new Set([
{ x: Math.max(pos.x - 1, 0), y: Math.max(pos.y - 1, 0) },
{ x: Math.max(pos.x - 1, 0), y: pos.y },
{ x: Math.max(pos.x - 1, 0), y: Math.min(pos.y + 1, lines.length - 1) },
{ x: Math.min(pos.xEnd + 1, (pos.line).length), y: Math.max(pos.y - 1, 0) },
{ x: Math.min(pos.xEnd + 1, (pos.line).length), y: pos.y },
{ x: Math.min(pos.xEnd + 1, (pos.line).length), y: Math.min(pos.y + 1, lines.length - 1) }
])]
for (let x = pos.x; x <= pos.xEnd; x++) {
directions.push({ x: x, y: Math.max(pos.y - 1, 0) })
directions.push({ x: x, y: Math.min(pos.y + 1, lines.length - 1) })
}
directions.forEach(direction => {
if (result === true) {
return true
}
if (findStructure(lines, direction.x, direction.y)) {
result = true
}
})
return result
}