-
Notifications
You must be signed in to change notification settings - Fork 0
/
day03.js
116 lines (84 loc) · 2.26 KB
/
day03.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
const fs = require("fs");
const array = fs
.readFileSync("day03.txt", { encoding: "utf-8" })
.split("\n")
.filter((x) => Boolean(x));
const myFunction = (array) => {
const bitLength = array[0].length;
let zeros = Array(bitLength).fill(0);
let ones = Array(bitLength).fill(0);
let gamma = "";
let epsilon = "";
for (let i = 0; i < array.length; i++) {
const bits = Array.from(array[i]);
for (let x = 0; x < bits.length; x++) {
if (bits[x] === "0") {
zeros[x]++;
}
if (bits[x] === "1") {
ones[x]++;
}
}
}
for (let i = 0; i < bitLength; i++) {
let gammaBit = 0;
let epsilonBit = 0;
if (ones[i] > zeros[i]) {
gammaBit = 1;
epsilonBit = 0;
}
if (zeros[i] > ones[i]) {
gammaBit = 0;
epsilonBit = 1;
}
gamma += gammaBit;
epsilon += epsilonBit;
}
return parseInt(gamma, 2) * parseInt(epsilon, 2);
};
const value = myFunction(array);
console.log(value);
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //
const myFunction2 = (array) => {
const bitLength = array[0].length;
let zeros = Array(bitLength).fill(0);
let ones = Array(bitLength).fill(0);
for (let i = 0; i < array.length; i++) {
const bits = Array.from(array[i]);
for (let x = 0; x < bits.length; x++) {
if (bits[x] === "0") {
zeros[x]++;
}
if (bits[x] === "1") {
ones[x]++;
}
}
}
return { zeros, ones };
};
const getOxygen = (array, i = 0) => {
const { zeros, ones } = myFunction2(array);
let mostCommonBit = "1";
if (zeros[i] > ones[i]) {
mostCommonBit = "0";
}
const filteredArray = array.filter((bits) => bits[i] === mostCommonBit);
if (filteredArray.length === 1) {
return filteredArray[0];
}
return getOxygen(filteredArray, i + 1);
};
const getCo2 = (array, i = 0) => {
const { zeros, ones } = myFunction2(array);
let leastCommonBit = "0";
if (zeros[i] > ones[i]) {
leastCommonBit = "1";
}
const filteredArray = array.filter((bits) => bits[i] === leastCommonBit);
if (filteredArray.length === 1) {
return filteredArray[0];
}
return getCo2(filteredArray, i + 1);
};
const value2 = parseInt(getOxygen(array), 2) * parseInt(getCo2(array), 2);
console.log(value2);