diff options
author | 2020-12-14 12:10:49 +0100 | |
---|---|---|
committer | 2020-12-14 12:10:49 +0100 | |
commit | 2f7c1f10323a26dea066eecb52b1c3fae746c0f5 (patch) | |
tree | 88dc34b4df1178d6c04726ac8aa75dc28edd5dc9 /day14/day14-2.js | |
parent | a1cb1a1b16b2304ee2c688e289395c65e4d7a657 (diff) | |
download | advent_of_code_2020-2f7c1f10323a26dea066eecb52b1c3fae746c0f5.tar.gz advent_of_code_2020-2f7c1f10323a26dea066eecb52b1c3fae746c0f5.tar.bz2 advent_of_code_2020-2f7c1f10323a26dea066eecb52b1c3fae746c0f5.zip |
day14
Diffstat (limited to 'day14/day14-2.js')
-rw-r--r-- | day14/day14-2.js | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/day14/day14-2.js b/day14/day14-2.js new file mode 100644 index 0000000..c9b2f0c --- /dev/null +++ b/day14/day14-2.js @@ -0,0 +1,48 @@ +const data = require('./data') +const splitted = data + .split(/mask = /g) + .filter(d => d !== '\n') + .map(d => d.split(/\n/g)) + .map(d => d.map((a, i) => (i > 0 ? a.match(/\d+/g) : a)).filter(a => a)) + .map(d => d.map((a, i) => (i > 0 ? a.map(b => parseInt(b).toString(2).padStart(36, '0')) : a))) + +const allVariations = (str, arr) => { + let i = str.indexOf('X'); + + if (i < 0) { + arr.push(str); + return; + } + + const splitStr = str.split(''); + let addZero = splitStr.slice(); + let addOne = splitStr.slice(); + + addZero.splice(i, 1, '0'); + addOne.splice(i, 1, '1'); + + allVariations(addZero.join(''), arr); + allVariations(addOne.join(''), arr ); +} + +const mem = {} +splitted.forEach(s => { + const mask = s[0] + const applyMask = (str) => ( + str.split('').map((v, i) => (mask[i] === '0' ? v : mask[i])).join('') + ) + + let variations + s.forEach((m, i) => { + variations = [] + if (i > 0) { + allVariations(applyMask(m[0]), variations) + variations.forEach(a => { + mem[parseInt(a, 2)] = parseInt(m[1], 2) + }) + } + }) +}) + +const sum = Object.values(mem).reduce((a, b) => a + b, 0) +console.log('Answer: ', sum) |