Published
Edited
Dec 6, 2021
2 stars
Insert cell
Insert cell
Insert cell
tidy = data.flatMap(d => d.split("").map((digit, position) => ({digit, position})))
Insert cell
part1 = {
let gamma = "", epsilon = "";
for (let i = 0; i < data[0].length; i++) {
const c = mostCommon(data, i);
gamma += c;
epsilon += 1 - c;
}
return parseInt(gamma, 2) * parseInt(epsilon, 2);
}
Insert cell
mostCommon = (numbers, i) => {
const counts = { 1: 0, 0: 0 };
for (const n of numbers) counts[n[i]]++;
return counts[0] > counts[1] ? 0 : 1;
}
Insert cell
function filter(input, criteria, i = 0) {
const match = criteria(input, i);
const remaining = input.filter((n) => n[i] == match);
return remaining.length === 1
? remaining[0]
: filter(remaining, criteria, i + 1);
}
Insert cell
o2 = parseInt(filter(data, mostCommon), 2)
Insert cell
co2 = parseInt(filter(data, (input, i) => 1 - mostCommon(input, i)), 2)
Insert cell
part2 = o2 * co2
Insert cell
Insert cell
data = (which === "test" ? test : input).trim().split("\n")
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