Published
Edited
Dec 7, 2021
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
calculateGamma = (data) => {
const bitCount = data[0].length;
// secure zeroed arrays of proper length
// count of number of 1s in a column
const count = new Array(bitCount).fill(0);
data.forEach(t => t.map((k, i) => count[i] += k));
// most common bit is either 0 or 1
// uses the fact that true/false * number = number/0
const mostCommon = new Array(bitCount).fill(0);
count.forEach((k, i) => mostCommon[i] = (k > (data.length / 2)) * 1);
// glue all zeroes and ones to a single string and convert to integer
return parseInt(mostCommon.join(""), 2); //
}
Insert cell
powerConsumption = (data) => {
const gamma = calculateGamma(data);
// epsilon is gamma’s two’s complement
const epsilon = (2 ** data[0].length) - gamma - 1;
return ({gamma, epsilon, power: gamma * epsilon});
}
Insert cell
Insert cell
testGamma = calculateGamma(testData)
Insert cell
assert(testGamma, 22)
Insert cell
testPower = powerConsumption(testData)
Insert cell
assert(testPower.power, 198)
Insert cell
Insert cell
assert(calculateGamma(realData), 2635)
Insert cell
realPower = powerConsumption(realData)
Insert cell
part1 = (data) => powerConsumption(data).power
Insert cell
**${AOC.timer(part1, realData, 1000)}**
Insert cell
assert(realPower.power, 3847100)
Insert cell
Insert cell
Insert cell
function lifeSupportrating(list, flip = 0, i = 0) {

// to make switching between two arrays easy
// collect the 0s and 1s at position i as an array
const lists = [
list.filter(k => !k[i]),
list.filter(k => k[i]),
];

// winner depends on longest list and flip
const winner = lists[0].length > lists[1].length
? lists[(flip + 0) % 2]
: lists[(flip + 1) % 2];
return winner.length === 1
? parseInt(winner[0].join(""), 2)
: lifeSupportrating(winner, flip, i + 1);
}
Insert cell
assert(lifeSupportrating(testData, 0), 23)
Insert cell
assert(lifeSupportrating(testData, 1), 10)
Insert cell
assert(lifeSupportrating(testData, 0) * lifeSupportrating(testData, 1), 230)
Insert cell
Insert cell
assert(lifeSupportrating(realData, 0) * lifeSupportrating(realData, 1), 4105235)
Insert cell
part2 = (data) => lifeSupportrating(data, 0) * lifeSupportrating(data, 1)
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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