-
Notifications
You must be signed in to change notification settings - Fork 0
/
part_2.dart
76 lines (61 loc) · 1.5 KB
/
part_2.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
import 'dart:io';
int totalScratchcards() {
try {
final file = File('Dart/Day4/input.txt');
final lines = file.readAsLinesSync();
final s = <String>[];
for (final line in lines) {
s.add(line);
}
var total = 0;
final multiString = <int, int>{};
for (var i = 0; i < s.length; i++) {
multiString[i] = 1;
}
for (var i = 0; i < s.length; i++) {
final game = s[i].split(': ');
final games = game[1].split('|');
final left = games[0].split(' ');
final right = games[1].split(' ');
final leftNumbers = parseNumbers(left);
final rightNumbers = parseNumbers(right);
final matches = intersection(leftNumbers, rightNumbers);
final multiplier = multiString[i];
total += multiplier!;
for (var j = 0; j < matches.length; j++) {
multiString[i + j + 1] = (multiString[i + j + 1] ?? 0) + multiplier;
}
}
print(total);
return total;
} catch (e) {
print('Error: $e');
return 0;
}
}
List<int> parseNumbers(List<String> nums) {
final result = <int>[];
for (final n in nums) {
if (n.isEmpty) {
continue;
}
final val = int.tryParse(n.trim());
if (val != null) {
result.add(val);
}
}
return result;
}
List<int> intersection(List<int> a, List<int> b) {
final result = <int>[];
final seen = <int, bool>{};
for (final v in a) {
seen[v] = true;
}
for (final v in b) {
if (seen[v] == true) {
result.add(v);
}
}
return result;
}