57 lines
1.5 KiB
TypeScript
57 lines
1.5 KiB
TypeScript
import path from 'path';
|
|
import { readFile } from "../utils";
|
|
|
|
let input = readFile(path.resolve(__dirname, 'input.txt'));
|
|
const size = input[0].length;
|
|
let bucket = Array(size).fill(0).map(x => Object.assign({}, [0, 0]));
|
|
|
|
const toDecimal = (binary) => parseInt(binary, 2);
|
|
|
|
|
|
input.map((x: string) => {
|
|
x.split('')
|
|
.map((c: string, idx: number) => {
|
|
if (c === '0') bucket[idx][0]++; else bucket[idx][1]++
|
|
})
|
|
})
|
|
|
|
const MSB = bucket.map(x => x[0] < x[1] ? "0" : "1").join("");
|
|
const LSB = bucket.map(x => x[0] < x[1] ? "1" : "0").join("");
|
|
|
|
let gamma = toDecimal(MSB)
|
|
let eps = toDecimal(LSB)
|
|
|
|
const power = gamma * eps;
|
|
|
|
console.log("Part 1: ", power);
|
|
|
|
const getBitCrit = (array, MSB, eqValue) => {
|
|
let tmpArray = [...array];
|
|
|
|
for (const idx in [...Array(size).keys()]) {
|
|
|
|
let count = [0, 0];
|
|
let keepMe;
|
|
|
|
// Count 0/1 values
|
|
tmpArray.forEach((x: string) => {
|
|
x[idx] === "0" ? count[0]++ : count[1]++;
|
|
})
|
|
|
|
// Swap results if we look for the least common value
|
|
if (!MSB) count = [count[1], count[0]]
|
|
|
|
// Which value to keep
|
|
if (count[0] === count[1]) keepMe = eqValue;
|
|
else keepMe = count[0] < count[1] ? '1' : '0'
|
|
|
|
// Filter
|
|
tmpArray = tmpArray.filter((x: string) => x[idx] === keepMe)
|
|
|
|
if (tmpArray.length === 1) return tmpArray[0];
|
|
}
|
|
}
|
|
|
|
const oxygen = toDecimal(getBitCrit(input, true, "1"));
|
|
const co2 = toDecimal(getBitCrit(input, false, "0"));
|
|
console.log("Part 2: ", oxygen * co2); |