Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | 2x 2x 2x 131x 98x 33x 12x 21x 2x 1x 1x 1x 1x 1x 11x 11x 10x 11x 7x 11x 1x 2x 1x 1x 1x 1x 11x 28x 1x 1x 28x 28x 26x 37x 5x 5x 28x 25x 38x 2x 2x 11x 1x 2x | const { readFile } = require('../helpers/file') const { sum } = require('../helpers/math') const isAdjacentSymbol = (potentialAdjacentSymbol, item) => { if (item === undefined || potentialAdjacentSymbol === undefined) { return false } if (isNaN(parseInt(item.value))) { return false } return ( potentialAdjacentSymbol.type != item.type && item.type === 'number' && potentialAdjacentSymbol.position <= item.position + item.value.length ) } const buildMatrix = (input) => { const data = readFile(input) const findDigitsRgx = new RegExp('(\\d+)', 'gm') const findSymbolsRgx = new RegExp('[^\\d.\\n]', 'gm') const symbolsDigitsMatrix = [] for (const line of data) { const lineMatrix = [] while ((match = findDigitsRgx.exec(line)) !== null) { lineMatrix.push({ value: match[0], type: 'number', position: match.index, }) } while ((match = findSymbolsRgx.exec(line)) != null) { lineMatrix.push({ value: match[0], type: 'symbol', position: match.index, }) } symbolsDigitsMatrix.push(lineMatrix) } return symbolsDigitsMatrix } const resolvePuzzle = (filePath) => { const matrix = buildMatrix(filePath) const elligibleNumbers = [] let i = 0 for (const row of matrix) { for (let j = 0; j <= row.length; j++) { // Check neighbors if (isAdjacentSymbol(row[j + 1], row[j])) { elligibleNumbers.push(parseInt(row[j].value)) delete matrix[i][j + 1] } Iif (isAdjacentSymbol(row[j - 1], row[j])) { elligibleNumbers.push(parseInt(row[j].value)) delete matrix[i][j - 1] } if (matrix[i + 1] !== undefined) { for (let k = 0; k < matrix[i + 1].length; k++) { if (isAdjacentSymbol(matrix[i + 1][k], row[j])) { elligibleNumbers.push(parseInt(row[j].value)) delete matrix[i + 1][j] } } } if (matrix[i - 1] !== undefined) { for (let k = 0; k < matrix[i - 1].length; k++) { if (isAdjacentSymbol(matrix[i - 1][k], row[j])) { elligibleNumbers.push(parseInt(row[j].value)) delete matrix[i - 1][j] } } } } i++ } return sum(elligibleNumbers) } module.exports = { resolvePuzzle } |