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 | 1x 1x 1x 1x 1x 1x 1x 455271x 455271x 455271x 1x 243x 243x 243x 1x 12x 3072x 12x 4066x 4066x 2006x 2006x 2006x 2023x 2006x 1162x 844x 4066x 2060x 527360x 449180x 527360x 891x 12x 1x 2x 2x 512x 241x 2x 1x | const { runHashAlgorithm } = require('./puzzle1') const { readFile } = require('../helpers/file') const resolvePuzzle = (fileInput) => { const data = readFile(fileInput)[0] const box = buildLensesBox(data) return resolveFocusingPowerOfLens(box) } const extractLabel = (str) => { const regex = new RegExp('([a-z])+', 'gm') const matches = regex.exec(str) return matches[0] } const extractDigitValue = (str) => { const regex = new RegExp('(\\d)', 'gm') const matches = regex.exec(str) return parseInt(matches[0]) } const buildLensesBox = (str) => { const arr = str.split(',') const lensesBox = new Array(256).fill().map(() => []) for (const element of arr) { const label = extractLabel(element) if (element.includes('=')) { const futureIndexOfElement = runHashAlgorithm(label) const value = element.replace('=', ' ') const indexToUpdate = lensesBox[futureIndexOfElement].findIndex( (el) => extractLabel(el) === label ) if (indexToUpdate === -1) { lensesBox[futureIndexOfElement].push(value) } else { lensesBox[futureIndexOfElement][indexToUpdate] = value } } if (element.includes('-')) { for (let rowIndex = 0; rowIndex < lensesBox.length; rowIndex++) { const indexToRemove = lensesBox[rowIndex].findIndex( (el) => extractLabel(el) === label ) if (indexToRemove !== -1) { lensesBox[rowIndex].splice(indexToRemove, 1) } } } } return lensesBox } const resolveFocusingPowerOfLens = (lensesBox) => { let total = 0 for (let i = 0; i < lensesBox.length; i++) { for (let j = 0; j < lensesBox[i].length; j++) { // i represents box #ID, j represents slot id total = total + (i + 1) * (j + 1) * extractDigitValue(lensesBox[i][j]) } } return total } module.exports = { resolvePuzzle, buildLensesBox, extractLabel, extractDigitValue, resolveFocusingPowerOfLens, } |