this repo has no description
at main 83 lines 2.3 kB view raw
1import { sumArray } from "../lib/util.ts"; 2 3export function solvePart1(input: string) { 4 const operations = parseInput(input); 5 console.log(operations); 6 7 const solutions = operations.map(({ op, values }) => { 8 const transformedValues = values.map((val) => Number(val.trim())); 9 if (op === "+") { 10 return transformedValues.reduce((sum, val) => sum + val, 0); 11 } else { 12 return transformedValues.reduce((prod, val) => prod * val, 1); 13 } 14 }); 15 16 return String(sumArray(solutions)); 17} 18 19export function solvePart2(input: string) { 20 const operations = parseInput(input); 21 22 const solutions = operations.map(({ op, values }) => { 23 const valueDigits = values.map((val) => 24 String(val).split("").map((char) => char === " " ? null : Number(char)) 25 ); 26 27 const transformedValues = transposeMatrix(valueDigits).map((col) => 28 digitsToNumber(col.filter((digit) => digit !== null)) 29 ); 30 31 if (op === "+") { 32 return transformedValues.reduce((sum, val) => sum + val, 0); 33 } else { 34 return transformedValues.reduce((prod, val) => prod * val, 1); 35 } 36 }); 37 38 return String(sumArray(solutions)); 39} 40 41type Operation = { 42 op: "+" | "*"; 43 values: string[]; 44}; 45 46function parseInput(input: string): Operation[] { 47 const rows = input.split("\n"); 48 // Remove the last empty row if present 49 if (rows[rows.length - 1] === "") { 50 rows.pop(); 51 } 52 53 const valuesRows = rows.slice(0, -1); 54 const operationRow = rows.at(-1)!; 55 56 const operations: Operation[] = []; 57 58 const opColRegex = /(?:(?<op>\*|\+)\s*\s)/g; 59 60 const matches = operationRow.matchAll(opColRegex); 61 62 const matchesArray = Array.from(matches); 63 for (const [index, match] of matchesArray.entries()) { 64 const isLast = matchesArray.length - 1 === index; 65 const colWidth = match[0]!.length - Number(!isLast); 66 const op = match.groups!.op as "+" | "*"; 67 68 const values = valuesRows.map((row) => 69 row.slice(match.index!, match.index! + colWidth) 70 ); 71 operations.push({ op, values }); 72 } 73 74 return operations; 75} 76 77function transposeMatrix<T>(matrix: T[][]): T[][] { 78 return matrix[0]!.map((_, colIndex) => matrix.map((row) => row[colIndex]!)); 79} 80 81function digitsToNumber(digits: number[]): number { 82 return digits.reduce((num, digit) => num * 10 + digit, 0); 83}