Files
advent-of-code-2021-firebase/functions/src/day3.ts

63 lines
1.7 KiB
TypeScript

import Utils from "./utils";
import Day from "./day";
class Day3 implements Day {
public part1(input: string[]): number {
const sums = Utils.zeroes(input[0].length);
for (const value of input) {
for (let i = 0; i < value.length; i++) {
if (value[i] === "1") {
sums[i] += 1;
}
}
}
const gamma = parseInt(sums.map(s => s > input.length / 2 ? "1" : "0").join(""), 2);
const epsilon = parseInt(sums.map(s => s <= input.length / 2 ? "1" : "0").join(""), 2);
return gamma * epsilon;
}
public part2(input: string[]): number {
return Day3.findLifeSupportRating(input, "oxygen") * Day3.findLifeSupportRating(input, "CO2");
}
static findLifeSupportRating(input: string[], type: "oxygen" | "CO2"): number {
const bits = input[0].length;
let indexesLeft = input.map((v, i) => i);
for (let bit = 0; bit < bits; bit++) {
const onesIdxs = indexesLeft.filter(j => input[j][bit] === "1")
const ones = onesIdxs.length;
if (ones >= indexesLeft.length / 2) {
// 1 is the most common, or they are equally common
if (type === "oxygen") {
indexesLeft = onesIdxs;
} else {
indexesLeft = indexesLeft.filter(j => input[j][bit] === "0")
}
} else {
// 0 is the most common
if (type === "oxygen") {
indexesLeft = indexesLeft.filter(j => input[j][bit] === "0")
} else {
indexesLeft = onesIdxs;
}
}
if (indexesLeft.length === 1) {
return parseInt(input[indexesLeft[0]], 2);
}
}
throw Error("More than one number left: " + JSON.stringify(indexesLeft));
}
}
export default Day3;