-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart_1.dart
121 lines (98 loc) · 2.51 KB
/
part_1.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import 'dart:collection';
import 'dart:io';
class SubMapping {
int source, size, offset;
SubMapping({required this.source, required this.size, required this.offset});
}
class Mapping extends ListMixin<SubMapping> {
final List<SubMapping> _list = [];
@override
int length = 0;
@override
SubMapping operator [](int index) => _list[index];
@override
void operator []=(int index, SubMapping value) {
_list[index] = value;
}
@override
void add(SubMapping value) {
_list.add(value);
length = _list.length;
}
}
int lowestLocationSeedNumber() {
try {
final file = File('Dart/Day5/input.txt');
final lines = file.readAsLinesSync();
final seeds = <int>[];
final mappings = <Mapping>[];
var currentMapping = Mapping();
for (final line in lines) {
if (line.isEmpty) {
continue;
}
if (line.contains("seeds: ")) {
final seedsString = line.split("seeds: ");
final seedList = seedsString[1].split(" ");
for (final seedItem in seedList) {
final seed = int.tryParse(seedItem);
if (seed != null) {
seeds.add(seed);
}
}
continue;
}
if (line.contains("-")) {
if (currentMapping.isNotEmpty) {
mappings.add(currentMapping);
}
currentMapping = Mapping();
continue;
}
final values = line.split(' ');
final source = int.tryParse(values[1]);
final size = int.tryParse(values[2]);
if (source == null || size == null) {
print("Error converting source or size to integer");
return 0;
}
final offset = sti(values[0]) - sti(values[1]);
currentMapping.add(SubMapping(
source: source,
size: size,
offset: offset,
));
}
if (currentMapping.isNotEmpty) {
mappings.add(currentMapping);
}
var lowest = -1;
for (final seed in seeds) {
var val = seed;
for (final mapping in mappings) {
for (final subMapping in mapping) {
if (val >= subMapping.source &&
val <= subMapping.source + subMapping.size) {
val += subMapping.offset;
break;
}
}
}
if (lowest == -1 || val < lowest) {
lowest = val;
}
}
print(lowest);
return lowest;
} catch (e) {
print('Error: $e');
return 0;
}
}
int sti(String s) {
final i = int.tryParse(s);
if (i == null) {
print("Error converting string to integer");
}
return i ?? 0;
}