| import { readFileSync } from "fs"; |
| |
| const input = readFileSync('./input.txt').toString().split('\n'); |
| |
| type coord = `${number}:${number}` |
| |
| const coords: Record<coord, string> = {}; |
| |
| const ignoreCoords: coord[] = [] |
| |
| function formatCoords(x: number, y: number): coord {return `${x}:${y}`} |
| |
| // INPUT CURRENT COORDS |
| function checkNumChar(x: number, y: number, currentNum?: string): undefined | string { |
| if (ignoreCoords.includes(formatCoords(x,y))) return |
| currentNum = currentNum ?? "" |
| const char = input[y][x]; |
| if(isNaN(parseInt(char))) return currentNum; |
| ignoreCoords.push(formatCoords(x,y)) |
| currentNum += char; |
| return checkNumChar(x+1, y, currentNum); |
| } |
| |
| let i = 0; |
| for(const line of input) { |
| let j = 0; |
| for (const char of line) { |
| if (char === ".") { |
| j++; |
| continue; |
| } else if(isNaN(parseInt(char))) { |
| coords[formatCoords(j,i)] = char |
| } else { |
| const num = checkNumChar(j,i); |
| // console.log(num) |
| if(num) coords[formatCoords(j,i)] = num as string |
| } |
| j++; |
| } |
| i++; |
| } |
| |
| // Part 1 |
| let sum = 0; |
| for(const [loc, val] of Object.entries(coords)) { |
| if(isNaN(parseInt(val))) continue; |
| |
| // Parse Coords |
| const [x,y] = loc.match(/\d+/g)!.map(s => parseInt(s)) as [number, number] |
| |
| // Check Next Door |
| const lx = x-1; |
| const rx = x + 1 + val.length; |
| |
| if( |
| coords[formatCoords(lx,y)] || |
| coords[formatCoords(rx,y)] |
| ) { |
| sum += parseInt(val); |
| continue; |
| } |
| |
| // Check Above / Below w/ diagonals |
| const ay = y - 1; |
| const by = y + 1; |
| |
| for(let i = -1; i <= val.length; i++) { |
| if( |
| coords[formatCoords(x+i, ay)] || |
| coords[formatCoords(x+i, by)] |
| ) { |
| sum += parseInt(val) |
| break; |
| } |
| } |
| } |
| |
| console.log(sum); |