-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday3question1.ts
More file actions
78 lines (59 loc) · 1.93 KB
/
day3question1.ts
File metadata and controls
78 lines (59 loc) · 1.93 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
// Could be done via bitmasking, arguably that would be easier, since dealing with indeces opens you up to offby1 issues
// I decided to deal in indeces, might refactor later (ha)
import { readFileSync } from "fs";
class BitCounter {
private zeroCount: number = 0;
private oneCount: number = 0;
public record(bitValue: number) {
if (bitValue === 0) {
this.zeroCount++;
} else if (bitValue === 1) {
this.oneCount++;
}
}
public getMostCommonBit(): number {
this.verifyUnevenFrequency();
return this.zeroCount > this.oneCount ? 0 : 1;
}
public getLeastCommonBit(): number {
this.verifyUnevenFrequency();
return this.zeroCount < this.oneCount ? 0 : 1;
}
private verifyUnevenFrequency() {
if (this.zeroCount === this.oneCount) {
throw new Error(
"Neither bit value is more common, both have: " + this.zeroCount
);
}
}
}
let inputs: string[];
const rawData = readFileSync("./day3inputs.txt", "utf8");
inputs = rawData.split("\r\n");
const bitLengthOfInput = inputs[0].length;
const bitCounters: BitCounter[] = [];
for (let i = 0; i < bitLengthOfInput; i++) {
bitCounters.push(new BitCounter());
}
for (let input of inputs) {
input.split("").forEach((bitValue, bitIndex) => {
bitCounters[bitIndex].record(Number(bitValue));
});
}
const binaryGammaRate = bitCounters.reduce<string>(
(partialReduction, currentBitCounter) => {
return partialReduction + String(currentBitCounter.getMostCommonBit());
},
""
);
const binaryEpsilonRate = bitCounters.reduce<string>(
(partialReduction, currentBitCounter) => {
return partialReduction + String(currentBitCounter.getLeastCommonBit());
},
""
);
const gammaRate = parseInt(binaryGammaRate, 2);
const epsilonRate = parseInt(binaryEpsilonRate, 2);
console.log(gammaRate);
console.log(epsilonRate);
console.log(gammaRate * epsilonRate);