-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday10.dart
86 lines (74 loc) · 1.65 KB
/
day10.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import './utils.dart';
Map<String, String> matches = {
'{': '}',
'(': ')',
'<': '>',
'[': ']',
};
Map<String, int> rewards = {
')': 3,
']': 57,
'}': 1197,
'>': 25137,
};
Map<String, int> rewards2 = {
')': 1,
']': 2,
'}': 3,
'>': 4,
};
int solve(List<String> lines) {
List<String> illegal = [];
// first
lines.forEach((line) {
List<String> stack = [];
for (int i = 0; i < line.length; i++) {
String c = line[i];
if (['[', '(', '{', '<'].contains(c)) {
stack.add(c);
} else {
String opening = stack.removeLast();
if (matches[opening] != c) {
illegal.add(c);
break;
}
}
}
});
// return illegal.fold(0, (int acc, String c) {
// return acc + rewards[c]!;
// });
// second
List<List<String>> endings = [];
lines.forEach((line) {
List<String> stack = [];
for (int i = 0; i < line.length; i++) {
String c = line[i];
if (['[', '(', '{', '<'].contains(c)) {
stack.add(c);
} else {
String opening = stack.removeLast();
if (matches[opening] != c) {
stack = [];
break;
}
}
}
if (stack.length > 0) {
endings.add(
new List.from(stack.map((c) => matches[c] ?? '').toList().reversed));
}
});
List<int> scores = endings.map((ending) {
return ending.fold(0, (int acc, String c) {
return acc * 5 + rewards2[c]!;
});
}).toList();
scores.sort((a, b) => a - b);
return scores[(scores.length / 2).round() - 1];
}
void main() async {
List<String> lines = await readlines('day10.txt');
int result = solve(lines);
print(result);
}