import fs from "fs"; const input = fs.readFileSync("./input.txt").toString(); const lineLength = input.split("\n")[0].length; const chars = input.split("\n").slice(0, -1).join(""); const numbers = Array.from(chars.matchAll(/[\d]+/g)).map((match) => ({ number: Number(match[0]), position: { start: match.index || 0, end: (match.index || 0) + match[0].length, }, })); const symbols = Array.from(chars.matchAll(/[^\.\d]/g)).map((match) => ({ symbol: match[0], position: match.index || 0, })); const result = symbols .filter((symbol) => symbol.symbol === "*") .reduce((acc, symbol) => { const adjacentNumbers = numbers.filter( (number) => symbol.position === number.position.start - 1 || symbol.position === number.position.end || (symbol.position >= number.position.start - 1 - lineLength && symbol.position <= number.position.end - lineLength) || (symbol.position >= number.position.start - 1 + lineLength && symbol.position <= number.position.end + lineLength), ); return adjacentNumbers.length === 2 ? acc + adjacentNumbers[0].number * adjacentNumbers[1].number : acc; }, 0); console.log({ result });