-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday14.dart
85 lines (71 loc) · 2.28 KB
/
day14.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
import 'dart:math';
import 'package:tuple/tuple.dart';
import './utils.dart';
typedef Pair = Tuple2<String, String>;
int getLetterCount(Map<Pair, int> pairsCounter, String lastLetter, String x) {
int count = pairsCounter.entries.fold(0, (int count, entry) {
if (entry.key.item1 == x) {
return count + entry.value;
}
return count;
});
int modifier = x == lastLetter ? 1 : 0;
return count.round() + modifier;
}
List<String> getLetters(List<Pair> pairs) {
List<String> result = [];
pairs.forEach((p) {
result.add(p.item1);
result.add(p.item2);
});
return result.toSet().toList();
}
int solve(List<String> lines) {
// get initial pairs
Map<Pair, int> pairsCounter = {};
String polymer = lines[0];
for (int i = 0; i < polymer.length; i++) {
if (i + 1 < polymer.length) {
Pair p = Pair(polymer[i], polymer[i + 1]);
pairsCounter[p] = pairsCounter[p] != null ? pairsCounter[p]! + 1 : 1;
}
}
String lastLetter = polymer[polymer.length - 1]; // this will be useful too
// get rules
Map<Pair, List<Pair>> rules = lines.sublist(2).fold({}, (acc, line) {
List<String> parts = line.split(' -> ');
Pair initial = Pair(parts[0][0], parts[0][1]);
Pair out1 = Pair(initial.item1, parts[1]);
Pair out2 = Pair(parts[1], initial.item2);
acc[initial] = [out1, out2];
return acc;
});
int STEPS = 40;
List<String> letters;
// make transformations, for each pair new 2 pairs grows
for (int i = 0; i < STEPS; i++) {
Map<Pair, int> newPairsCounter = {};
pairsCounter.entries.forEach((entry) {
var outputs = rules[entry.key] ?? [];
int increment = entry.value;
for (Pair o in outputs) {
newPairsCounter[o] = newPairsCounter[o] != null
? newPairsCounter[o]! + increment
: increment;
}
});
pairsCounter = newPairsCounter;
}
// count the number of occurences of each letter
letters = getLetters(pairsCounter.keys.toList());
Map<String, int> letterCount = {};
letters.forEach((String l) {
letterCount[l] = getLetterCount(pairsCounter, lastLetter, l);
});
return letterCount.values.reduce(max) - letterCount.values.reduce(min);
}
void main() async {
List<String> lines = await readlines('day14.txt');
int result = solve(lines);
print(result);
}