-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday_3.js
More file actions
111 lines (80 loc) · 2.46 KB
/
Copy pathday_3.js
File metadata and controls
111 lines (80 loc) · 2.46 KB
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
/*
const fs = require('fs')
const getGammaRate = (binaries, length, bitIndex) => {
let count = 0
for (const binary of binaries) {
if(binary[bitIndex] === '1') {
count++
}
if (count > length/2) {
break
}
}
return count > (length/2) ? '1' : '0'
}
const getEpsilonRate = (gamma) => {
let epsilon = ''
for (let i=0; i<gamma.length; i++) {
epsilon += gamma[i] === '1' ? '0' : '1'
}
return epsilon
}
const binaryToInt = (binary) => parseInt(binary, 2)
fs.readFile('./inputs/3.txt', 'utf8', (err, response) => {
if (err) return err
const binaries = response.split('\n')
let gammaRate = ''
for(let bitIndex=0; bitIndex < binaries[0].length; bitIndex++) {
gammaRate += getGammaRate(binaries, binaries.length, bitIndex)
}
const powerConsumption = binaryToInt(gammaRate) * binaryToInt(
getEpsilonRate(gammaRate)
)
console.log(powerConsumption)
})
*/
const fs = require('fs')
const getRating = (binaries, length, bitIndex, tendency) => {
let count = 0
for (const binary of binaries) {
if(binary[bitIndex] === '1') {
count++
}
if (count > length/2) {
break
}
}
if (count > (length/2)) {
return tendency === 1 ? '1' : '0'
} else if (count < (length/2)) {
return tendency === 1 ? '0' : '1'
} else {
return tendency === 1 ? '1' : '0'
}
}
const binaryToInt = (binary) => parseInt(binary, 2)
fs.readFile('./inputs/3.txt', 'utf8', (err, response) => {
if (err) return err
const binaries = response.split('\n')
let o2diag = ''
let co2diag = ''
let cO2Rating = [...binaries]
let o2Rating = [...binaries]
for(let bitIndex=0; bitIndex < binaries[0].length; bitIndex++) {
o2diag += getRating(o2Rating, o2Rating.length, bitIndex, 1)
co2diag += getRating(cO2Rating, cO2Rating.length, bitIndex, 0)
if (cO2Rating.length > 1) {
cO2Rating = cO2Rating.filter((binary) => binary[bitIndex] === co2diag[bitIndex])
}
if (o2Rating.length > 1) {
o2Rating = o2Rating.filter((binary) => binary[bitIndex] === o2diag[bitIndex])
}
if (o2Rating.length === 1 && cO2Rating.length === 1) {
break
}
}
const lifeSupportRating = binaryToInt(cO2Rating[0]) * binaryToInt(o2Rating[0])
console.log({
lifeSupportRating
})
})