|
| 1 | +const isSymbol = (str: string): boolean => { |
| 2 | + return str !== "."; // numbers touching numbers is not the case, so handling only `.` |
| 3 | +}; |
| 4 | + |
| 5 | +const isNumber = (str: string): boolean => { |
| 6 | + return !Number.isNaN(parseInt(str)); |
| 7 | +}; |
| 8 | + |
| 9 | +const isGear = (str: string): boolean => { |
| 10 | + return str === "*"; |
| 11 | +}; |
| 12 | +export function gearRatioPartOne(content: string): number { |
| 13 | + const lines = content.trim().split("\n"); |
| 14 | + |
| 15 | + const matrix = lines.map((line) => line.split("")); |
| 16 | + |
| 17 | + let total = 0; |
| 18 | + |
| 19 | + for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) { |
| 20 | + let match; |
| 21 | + const pattern = /\d+/g; |
| 22 | + |
| 23 | + while ((match = pattern.exec(lines[lineIdx])) !== null) { |
| 24 | + const arround: boolean[] = []; |
| 25 | + |
| 26 | + // * Left |
| 27 | + // check if `lineIdx` or `match.index - 1` is negative |
| 28 | + if ( |
| 29 | + lineIdx >= 0 && |
| 30 | + match.index - 1 >= 0 && |
| 31 | + matrix[lineIdx] && |
| 32 | + matrix[lineIdx][match.index - 1] |
| 33 | + ) { |
| 34 | + const matrixLeft = matrix[lineIdx][match.index - 1]; |
| 35 | + arround.push(isSymbol(matrixLeft)); // * left side |
| 36 | + } |
| 37 | + |
| 38 | + // * Right |
| 39 | + if ( |
| 40 | + lineIdx >= 0 && |
| 41 | + pattern.lastIndex >= 0 && |
| 42 | + matrix[lineIdx] && |
| 43 | + matrix[lineIdx][pattern.lastIndex] |
| 44 | + ) { |
| 45 | + const matrixRight = matrix[lineIdx][pattern.lastIndex]; |
| 46 | + arround.push(isSymbol(matrixRight)); // * right side |
| 47 | + } |
| 48 | + |
| 49 | + for (let i = match.index - 1; i <= pattern.lastIndex; i++) { |
| 50 | + // * TOP ==================== |
| 51 | + // * Check if: |
| 52 | + // * - lineIdx - 1 is NOT negative |
| 53 | + // * - i is NOT negative |
| 54 | + // * - matrix[lineIdx - 1] is valid |
| 55 | + // * - matrix[lineIdx - 1][i] is valid |
| 56 | + if ( |
| 57 | + lineIdx - 1 >= 0 && |
| 58 | + i >= 0 && |
| 59 | + matrix[lineIdx - 1] && |
| 60 | + matrix[lineIdx - 1][i] |
| 61 | + ) { |
| 62 | + const matrixTop = matrix[lineIdx - 1][i]; |
| 63 | + arround.push(isSymbol(matrixTop)); |
| 64 | + } |
| 65 | + |
| 66 | + // * BOTTOM ==================== |
| 67 | + // check if lineIdx + 1 or i is negative, and is not bigger than the matrix length |
| 68 | + if ( |
| 69 | + lineIdx + 1 >= 0 && |
| 70 | + i >= 0 && |
| 71 | + matrix[lineIdx + 1] && |
| 72 | + matrix[lineIdx + 1][i] |
| 73 | + ) { |
| 74 | + const matrixBottom = matrix[lineIdx + 1][i]; |
| 75 | + arround.push(isSymbol(matrixBottom)); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + if (arround.includes(true)) { |
| 80 | + total += Number(match[0]); |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + return total; |
| 86 | +} |
0 commit comments