-
Notifications
You must be signed in to change notification settings - Fork 0
/
day3.dart
63 lines (51 loc) · 1.74 KB
/
day3.dart
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
import './utils.dart';
import 'package:tuple/tuple.dart';
String filterByIndex(
List<String> numbers, int index, String atu, String operation) {
if (numbers.length == 1) {
return numbers[0];
}
int targetCounter = numbers.fold(0, (int acc, String n) {
return acc + int.parse(n[index]);
});
String targetChar = targetCounter < numbers.length / 2 ? '1' : '0';
if (operation == 'gt') {
targetChar = targetCounter > numbers.length / 2 ? '1' : '0';
}
if (targetCounter == numbers.length / 2) {
targetChar = atu;
}
return filterByIndex(
numbers.where((String n) => n[index] == targetChar).toList(),
index + 1,
atu,
operation);
}
void solve(List<String> lines) {
List<int> acc = List.filled(lines[0].length, 0);
List<String> numbers = [];
// Sum "ones" for every column, also save parsed lines to separate array
lines.fold(acc, (List<int> accumulator, String line) {
List<int> lineValues =
line.trim().split('').map((String char) => int.parse(char)).toList();
numbers.add(lineValues.join(''));
lineValues.asMap().forEach((index, value) {
accumulator[index] += value;
});
return accumulator;
});
// first part
String gammaStr =
acc.map((e) => e > lines.length / 2 ? 1 : 0).toList().join('');
String epsilonStr =
acc.map((e) => e < lines.length / 2 ? 1 : 0).toList().join('');
print(int.parse(gammaStr, radix: 2) * int.parse(epsilonStr, radix: 2));
// second part
String o2genStr = filterByIndex(numbers, 0, '1', 'gt');
String co2scrubStr = filterByIndex(numbers, 0, '0', 'lt');
print(int.parse(o2genStr, radix: 2) * int.parse(co2scrubStr, radix: 2));
}
void main() async {
List<String> lines = await readlines('day3.txt');
solve(lines);
}