Published
Edited
Dec 3, 2021
Insert cell
Insert cell
Insert cell
power = (input) => {
const matrix = input.split("\n").map((num) => num.split(""));
const bits = matrix[0].length;
let gammaBits = [];
for (let i = 0; i < bits; i++) {
let zeroCount = 0,
oneCount = 0;
for (let j = 0; j < matrix.length; j++) {
if (matrix[j][i] === "0") zeroCount++;
else oneCount++;
}
gammaBits.push(zeroCount > oneCount ? 0 : 1);
}
const gamma = parseInt(gammaBits.join(""), 2),
epsilon = gamma ^ (2 ** gammaBits.length - 1);
return { gamma, epsilon, answer: gamma * epsilon };
}
Insert cell
test = power(testInput)
Insert cell
[
test.gamma.toString(2).padStart(5, "0"),
test.epsilon.toString(2).padStart(5, "0"),
]
Insert cell
// Remembering how to xor
22 ^ (2 ** 5 - 1)
Insert cell
Insert cell
Insert cell
part1 = power( input )
Insert cell
Insert cell
bit = 0b1
Insert cell
(0b1 << 6).toString(2)
Insert cell
getBit = (num, pos) => (num & (0b1 << (pos - 1)) ? 1 : 0)
Insert cell
[getBit(0b10000, 5), getBit(0b10101, 4), getBit(0b10101, 3)]
Insert cell
matchBit = (target, pos) => (num) => {
return getBit(num, pos) === target;
}
Insert cell
matchBit(1, 4)(0b11000)
Insert cell
lifeSupport = (input) => {
const lines = input.split("\n").map((n) => parseInt(n, 2));
const numBits = input.split("\n")[0].length;
let o2 = [...lines],
co2 = [...lines];

for (let i = 0; i < numBits && o2.length > 1; i++) {
const pos = numBits - i; // left most bit
let [zeros, ones] = o2.reduce(
(acc, num) => {
acc[getBit(num, pos)]++;
return acc;
},
[0, 0]
);
// return [zeros, ones];
let target = zeros === ones ? 1 : zeros > ones ? 0 : 1;
o2 = o2.filter(matchBit(target, pos));
}

for (let i = 0; i < numBits && co2.length > 1; i++) {
const pos = numBits - i; // left most bit
let [zeros, ones] = co2.reduce(
(acc, num) => {
acc[getBit(num, pos)]++;
return acc;
},
[0, 0]
);
let target = zeros === ones ? 0 : zeros < ones ? 0 : 1;
co2 = co2.filter(matchBit(target, pos));
}

// return co2.map((n) => n.toString(2).padStart(numBits, "0"));
// return o2.map((n) => n.toString(2).padStart(numBits, "0"));

return { o2: o2[0], co2: co2[0], answer: o2[0] * co2[0] };
}
Insert cell
lifeSupport(testInput, test)
Insert cell
lifeSupport(input)
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more