import { takeWhile } from 'lodash'; import fs from "fs"; import {calculateMinimumCubePowers, calculatePossibleGames, parseGame} from "./day_two"; export class Engine { constructor(private readonly partNumbers: number[]) { } public static create(input: string): Engine { const lines = input.split('\n').filter(Boolean); const partRegex = /\d+/g; const symbolRegex = /[^a-zA-Z\d\.]/g; const parts : number[][] = new Array(lines.length).fill(0).map(() => new Array(lines[0].length)); const symbols: string[][] = new Array(lines.length).fill(0).map(() => new Array(lines[0].length)); lines.forEach((line, lineNumber) => { const matches = [...line.matchAll(partRegex)]; matches.map(match => { if (match && match.index !== undefined) { const parsedNumber = parseInt(match[0], 10); for (let i = match.index; i < match.index + match[0].length; i++) { parts[lineNumber][i] = parsedNumber; } } }); }); lines.forEach((line, lineNumber) => { const matches = [...line.matchAll(symbolRegex)]; matches.map(match => { if (match && match.index !== undefined) { symbols[lineNumber][match.index] = match[0]; } }); }); console.log(symbols.length, parts.length) const partsList = symbols.flatMap((row, rowIndex) => row.map((symbol, index) => { if (!symbol) return symbol; const partIndex = [ [rowIndex - 1, index - 1], [rowIndex - 1, index], [rowIndex - 1, index + 1], [rowIndex, index - 1], [rowIndex, index + 1], [rowIndex + 1, index - 1], [rowIndex + 1, index], [rowIndex + 1, index + 1] ]; return Array.from(new Set(partIndex.filter(([rowNum, col]) => rowNum >= 0 && rowNum <= symbols.length && index >= 0 && index <= row.length) .map(([rowNum, column]) => { return parts[rowNum][column] }).filter(Boolean))) .reduce((total, val) => total + val,0); }) ) return new Engine(partsList as number[]); } public sumPartNumbers(): number { return this.partNumbers.reduce((total, partNumber) => total + partNumber, 0); } } export const runDayThree = () => { const input = fs.readFileSync('./inputs/day_three_input.txt', 'utf8'); const engine = Engine.create(input) console.log(engine.sumPartNumbers()); }