From b2cb9c32d687eec0656ce60d4683c4a0512bc5db Mon Sep 17 00:00:00 2001 From: Nathan van Ofwegen Date: Sat, 4 Dec 2021 13:31:59 +0100 Subject: [PATCH] d3p2 --- src/day3/index.ts | 54 ++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 44 insertions(+), 10 deletions(-) diff --git a/src/day3/index.ts b/src/day3/index.ts index 991ebea..4062ef5 100644 --- a/src/day3/index.ts +++ b/src/day3/index.ts @@ -2,22 +2,56 @@ 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])); -input - .map((x: string) => { - x.split('') - .map((c, idx: number) => { - if (c === '0') bucket[idx][0]++; else bucket[idx][1]++ - }) - }) +const toDecimal = (binary) => parseInt(binary, 2); -let gamma = parseInt(bucket.map(x => x[0] < x[1] ? "0" : "1").join(""), 2) -let eps = parseInt(bucket.map(x => x[0] < x[1] ? "1" : "0").join(""), 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); \ No newline at end of file