From 0290242a25558a9ec6ece7ea8b2080ba932f8f07 Mon Sep 17 00:00:00 2001 From: Zach Willard <13011363+fullstackzach@users.noreply.github.com> Date: Sun, 12 Dec 2021 10:12:41 -0600 Subject: [PATCH] feat: day3 part 2 --- day3/day3.js | 49 +++++++++++++++++++++++++++++++++++++++++++++++ day3/day3.test.js | 45 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+) diff --git a/day3/day3.js b/day3/day3.js index 96f9ce8..3c08d81 100644 --- a/day3/day3.js +++ b/day3/day3.js @@ -76,6 +76,52 @@ function mostCommon(arr, bitIndex) { return -1 } +function reduceTargetBit(data, index, targetBit) { + return data.reduce((matchingVals, current) => { + if (Number.parseInt(current[index]) === targetBit) { + matchingVals.push(current) + } + return matchingVals + }, []) +} + +function flipAbit(bit) { + return bit === 0 ? 1 : 0 +} + +function oxygenGeneratorRating(data, index = 0) { + const result = mostCommon(data, index) + const commonBit = result === -1 ? 1 : result + + if (data.length === 1) { + return binaryStringToBase10(data[0]) + } + + const arr = reduceTargetBit(data, index, commonBit) + + return oxygenGeneratorRating(arr, ++index) +} + +function co2scrubberRating(data, index = 0) { + const result = mostCommon(data, index) + const leastCommonBit = result === -1 ? 0 : flipAbit(result) + + if (data.length === 1) { + return binaryStringToBase10(data[0]) + } + + const arr = reduceTargetBit(data, index, leastCommonBit) + + return co2scrubberRating(arr, ++index) +} + +function part2solution() { + const data = parse(diagnostics) + const oxyRating = oxygenGeneratorRating(data) + const co2Rating = co2scrubberRating(data) + return oxyRating * co2Rating +} + export { parse, calcGammaBits, @@ -83,4 +129,7 @@ export { binaryStringToBase10, part1solution, mostCommon, + oxygenGeneratorRating, + co2scrubberRating, + part2solution, } diff --git a/day3/day3.test.js b/day3/day3.test.js index aaf8923..aa67117 100644 --- a/day3/day3.test.js +++ b/day3/day3.test.js @@ -5,6 +5,9 @@ import { binaryStringToBase10, part1solution, mostCommon, + oxygenGeneratorRating, + co2scrubberRating, + part2solution, } from './day3.js' describe('parse data', () => { @@ -129,3 +132,45 @@ describe('Part 2 - mostCommon', () => { expect(mostCommon(parse(exampleData), 0)).toEqual(0) }) }) + +describe('Part 2 - oxygenGeneratorRating', () => { + test('with example data', () => { + const exampleData = `00100 +11110 +10110 +10111 +10101 +01111 +00111 +11100 +10000 +11001 +00010 +01010` + expect(oxygenGeneratorRating(parse(exampleData))).toEqual(23) + }) +}) + +describe('Part 2 - co2scrubberRating', () => { + test('with example data', () => { + const exampleData = `00100 +11110 +10110 +10111 +10101 +01111 +00111 +11100 +10000 +11001 +00010 +01010` + expect(co2scrubberRating(parse(exampleData))).toEqual(10) + }) +}) + +describe('Part 2 - final solution', () => { + test('with solution data', () => { + expect(part2solution()).toEqual(6677951) + }) +})