Created
December 14, 2020 05:48
-
-
Save sahibjotsaggu/1605db706f2d87d40c327eff5f19dbef to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let input1 = ``; | |
let input = input2.split("\n"); | |
function dec2bin(dec) { | |
return (dec >>> 0).toString(2); | |
} | |
function part1() { | |
const mem = {}; | |
let mask = ""; | |
for (let i = 0; i < input.length; i++) { | |
const [left, right] = input[i].split(" = "); | |
if (left === "mask") { | |
mask = right; | |
} else { | |
const memLoc = left.replace(/(mem\[|\])/g, ""); | |
const binVal = dec2bin(Number(right)); | |
const value = new Array(36 - binVal.length) | |
.fill("0") | |
.concat(binVal.split("")); | |
for (let m = 0; m < mask.length; m++) { | |
const maskBit = mask[m]; | |
if (maskBit !== "X") { | |
value[m] = maskBit; | |
} | |
} | |
mem[memLoc] = parseInt(value.join(""), 2); | |
} | |
} | |
console.log(Object.values(mem).reduce((a, b) => a + b, 0)); | |
} | |
function getXIndices(value) { | |
const res = []; | |
for (let i = 0; i < value.length; i++) { | |
if (value[i] === "X") { | |
res.push(i); | |
} | |
} | |
return res; | |
} | |
function part2() { | |
const mem = {}; | |
let mask = ""; | |
for (let i = 0; i < input.length; i++) { | |
const [left, right] = input[i].split(" = "); | |
if (left === "mask") { | |
mask = right; | |
} else { | |
const memLoc = left.replace(/(mem\[|\])/g, ""); | |
const binVal = dec2bin(Number(memLoc)); | |
const value = new Array(36 - binVal.length) | |
.fill("0") | |
.concat(binVal.split("")); | |
let xCounter = 0; | |
for (let m = 0; m < mask.length; m++) { | |
const maskBit = mask[m]; | |
if (maskBit !== "0") { | |
value[m] = maskBit; | |
} | |
if (maskBit === "X") { | |
xCounter++; | |
} | |
} | |
const xIndices = getXIndices(value); | |
for (let f = 0; f < Math.pow(2, xCounter); f++) { | |
const fMask = dec2bin(String(f)).padStart(xCounter, "0").split(""); | |
for (let h = 0; h < fMask.length; h++) { | |
value[xIndices[h]] = fMask[h]; | |
} | |
mem[parseInt(value.join(""), 2)] = Number(right); | |
} | |
} | |
} | |
console.log(Object.values(mem).reduce((a, b) => a + b, 0)); | |
} | |
part2(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment