-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathday03_diagnostic.ts
107 lines (93 loc) · 2.49 KB
/
day03_diagnostic.ts
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
"use strict";
import fs from "fs";
import assert from "assert";
import _ from "lodash";
const diagnosticReport: string[] = fs
.readFileSync("2021/data/day03_input.txt")
.toString()
.trim()
.split("\n");
const TEST_INPUT = `00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010
`
.trim()
.split("\n");
// part 1
const calculatePowerConsumption = (diagnosticReport: string[]) => {
const result: string[] = [];
const complement: string[] = [];
for (let i = 0; i < diagnosticReport[0].length; i++) {
let numOnes = 0;
for (const report of diagnosticReport) {
if (report[i] === "1") {
numOnes += 1;
}
}
if (numOnes > Math.floor(diagnosticReport.length / 2)) {
result.push("1");
complement.push("0");
} else {
result.push("0");
complement.push("1");
}
}
return parseInt(result.join(""), 2) * parseInt(complement.join(""), 2);
};
assert(calculatePowerConsumption(TEST_INPUT) == 198);
// part 2
const calculateO2Rating = (diagnosticReport: string[], keepValue: number) => {
let validReports: string[] = diagnosticReport.slice();
for (let i = 0; i < diagnosticReport[0].length; i++) {
let result = _.groupBy(validReports, (x) => x[i]);
if (result[0].length > result[1].length) {
validReports = result[0];
} else if (result[0].length < result[1].length) {
validReports = result[1];
} else {
if (keepValue == 1) {
validReports = result[1];
} else {
validReports = result[0];
}
}
if (validReports.length == 1) {
return parseInt(validReports[0], 2);
}
}
};
const calculateCO2Rating = (diagnosticReport: string[], keepValue: number) => {
let validReports: string[] = diagnosticReport.slice();
for (let i = 0; i < diagnosticReport[0].length; i++) {
let result = _.groupBy(validReports, (x) => x[i]);
if (result[0].length < result[1].length) {
validReports = result[0];
} else if (result[0].length > result[1].length) {
validReports = result[1];
} else {
if (keepValue == 1) {
validReports = result[1];
} else {
validReports = result[0];
}
}
if (validReports.length == 1) {
return parseInt(validReports[0], 2);
}
}
};
const test_o2 = calculateO2Rating(TEST_INPUT, 1);
console.log(test_o2);
const test_co2 = calculateCO2Rating(TEST_INPUT, 0);
console.log(test_co2);
console.log(calculateO2Rating(diagnosticReport, 1));
console.log(calculateCO2Rating(diagnosticReport, 0));