day 3
Signed-off-by: Jack Bond-Preston <jackbondpreston@outlook.com>
This commit is contained in:
parent
a7c2b7d368
commit
70eb8d1848
29
3/3a.js
Normal file
29
3/3a.js
Normal file
@ -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);
|
||||
|
32
3/3b.js
Normal file
32
3/3b.js
Normal file
@ -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));
|
Loading…
Reference in New Issue
Block a user