d3p2
This commit is contained in:
@@ -2,22 +2,56 @@ import path from 'path';
|
|||||||
import { readFile } from "../utils";
|
import { readFile } from "../utils";
|
||||||
|
|
||||||
let input = readFile(path.resolve(__dirname, 'input.txt'));
|
let input = readFile(path.resolve(__dirname, 'input.txt'));
|
||||||
|
|
||||||
const size = input[0].length;
|
const size = input[0].length;
|
||||||
let bucket = Array(size).fill(0).map(x => Object.assign({}, [0, 0]));
|
let bucket = Array(size).fill(0).map(x => Object.assign({}, [0, 0]));
|
||||||
|
|
||||||
input
|
const toDecimal = (binary) => parseInt(binary, 2);
|
||||||
.map((x: string) => {
|
|
||||||
|
|
||||||
|
input.map((x: string) => {
|
||||||
x.split('')
|
x.split('')
|
||||||
.map((c, idx: number) => {
|
.map((c: string, idx: number) => {
|
||||||
if (c === '0') bucket[idx][0]++; else bucket[idx][1]++
|
if (c === '0') bucket[idx][0]++; else bucket[idx][1]++
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
let gamma = parseInt(bucket.map(x => x[0] < x[1] ? "0" : "1").join(""), 2)
|
const MSB = bucket.map(x => x[0] < x[1] ? "0" : "1").join("");
|
||||||
let eps = parseInt(bucket.map(x => x[0] < x[1] ? "1" : "0").join(""), 2)
|
const LSB = bucket.map(x => x[0] < x[1] ? "1" : "0").join("");
|
||||||
|
|
||||||
|
let gamma = toDecimal(MSB)
|
||||||
|
let eps = toDecimal(LSB)
|
||||||
|
|
||||||
const power = gamma * eps;
|
const power = gamma * eps;
|
||||||
|
|
||||||
console.log("Part 1: ", power);
|
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);
|
||||||
Reference in New Issue
Block a user