From 70eb8d1848bb66e1dcde5d82d9664fdbf5e1ca26 Mon Sep 17 00:00:00 2001 From: Jack Bond-Preston Date: Sat, 11 Dec 2021 04:37:09 +0000 Subject: [PATCH] day 3 Signed-off-by: Jack Bond-Preston --- 3/3a.js | 29 +++++++++++++++++++++++++++++ 3/3b.js | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 3/3a.js create mode 100644 3/3b.js diff --git a/3/3a.js b/3/3a.js new file mode 100644 index 0000000..d3c20de --- /dev/null +++ b/3/3a.js @@ -0,0 +1,29 @@ +const fs = require('fs'); + +const data = fs.readFileSync("input.txt", "utf8").split("\n"); +const width = data[0].length; + +const result = data + .reduce((acc, val) => { + for (let c = 0; c < width; c++) { + if (val.charAt(c) === '1') { + acc[c] += 1; + } + } + + return acc; + }, Array(width).fill(0)) + .map(x => x > (data.length - 1) / 2) + .reduce((acc, val, index) => { + if (val) { + acc += Math.pow(2, (width - index - 1)); + } + + return acc; + }, 0); + +const epsilon = result; +const gamma = ~result & ~(-1 << width); + +console.log(epsilon * gamma); + diff --git a/3/3b.js b/3/3b.js new file mode 100644 index 0000000..83455c1 --- /dev/null +++ b/3/3b.js @@ -0,0 +1,32 @@ +const fs = require('fs'); + +const data = fs.readFileSync("input.txt", "utf8").split("\n"); +data.pop(); +const width = data[0].length; + +let results = [0, 0]; +let filtered; + +for (let x = 0; x <= 1; x++) { + filtered = data; + for (let i = 0; i < width && filtered.length > 1; i++) { + const numOnes = filtered + .reduce((acc, val) => { + if (val.charAt(i) === x.toString()) { + acc += 1; + } + return acc; + }, 0); + + let keep = x.toString(); + if (numOnes < filtered.length / 2) keep = '0'; + if (numOnes > filtered.length / 2) keep = '1'; + + filtered = filtered + .filter(x => x.charAt(i) === keep); + } + results[x] = parseInt(filtered[0], 2); +} + + +console.log(results.reduce((x, y) => x * y));