-
Notifications
You must be signed in to change notification settings - Fork 1
/
03.js
96 lines (91 loc) · 1.62 KB
/
03.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
'use strict';
/**
* @param {string} d
*/
export const part1 = async d => {
const bits = [];
d.split('\n').map(e=>{
e.split('').map((e, i) => {
if (bits[i] === undefined) {
bits[i] = 0;
}
if (e == '1') {
bits[i]++;
}
else {
bits[i]--;
}
});
});
const gamma = bits.map((e)=>(e>0) ? 1 : 0).reduce((p, c) => {
return (p << 1) + c;
}, 0);
const epsilon = ((1 << bits.length) - 1) ^ gamma;
return gamma * epsilon;
};
/**
* @param {string} d
*/
export const part2 = async d => {
const data = d.split('\n');
let oxg = data.slice(0);
let co2 = data.slice(0);
/**
*
* @param {[string]} data
* @param number pos
*/
const getBits = (data, pos) => {
const bits = [0, 0];
data.forEach(e => {
bits[+(e[pos] == '1')]++;
});
return bits;
};
/**
*
* @param {[string]} data
* @param {number} pos
* @param {string} bit
*/
const filter = (data, pos, bit) => {
return data.filter((e)=>{
return (e[pos] == bit);
});
};
// Find oxg value
{
let pos = 0;
while (oxg.length > 1) {
const bits = getBits(oxg, pos);
if (bits[0] > bits[1]) {
oxg = filter(oxg, pos, '0');
}
else if (bits[0] == bits[1]) {
oxg = filter(oxg, pos, '1');
}
else {
oxg = filter(oxg, pos, '1');
}
pos++;
}
}
// Find co2 value
{
let pos = 0;
while (co2.length > 1) {
const bits = getBits(co2, pos);
if (bits[0] < bits[1]) {
co2 = filter(co2, pos, '0');
}
else if (bits[0] == bits[1]) {
co2 = filter(co2, pos, '0');
}
else {
co2 = filter(co2, pos, '1');
}
pos++;
}
}
return parseInt(oxg[0], 2) * parseInt(co2[0], 2);
};