-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday9.dart
70 lines (60 loc) · 1.71 KB
/
day9.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
import 'dart:core';
import 'dart:io';
import 'dart:math';
import 'package:2022/data_structures.dart';
class Point extends Tuple<int, int> {
Point(super.x, super.y);
Point.copy(Point p) : super(p.x, p.y);
Point.origin() : super(0, 0);
void addV2(Vector2 v) {
x += v.x;
y += v.y;
}
int simpleDistanceFrom(Point p) =>
max<int>((x - p.x).abs(), (y - p.y).abs()).abs();
Vector2 normalisedVectorTo(Point p) {
var xDir = p.x - x;
var yDir = p.y - y;
xDir = max(-1, min(1, xDir));
yDir = max(-1, min(1, yDir));
return Vector2(xDir, yDir);
}
}
void day9() {
var lines = File("inputs/day9").readAsLinesSync();
print("Part 1:");
calculateTailPath(2, lines);
print("Part 2:");
calculateTailPath(10, lines);
}
void calculateTailPath(int ropeKnotCount, List<String> lines) {
var tailVisited = <Point>{Point.origin()};
var ropeKnots = List.generate(ropeKnotCount, (_) => Point.origin());
for (var line in lines) {
var split = line.split(" ");
var dir = split[0];
var v = Vector2.fromNormalisedDir(dir);
for (var steps = int.parse(split[1]); steps > 0; steps--) {
for (var i = 0; i < ropeKnotCount; i++) {
var knot = ropeKnots[i];
if (i == 0) {
// knot is head
knot.addV2(v);
} else {
var prevKnot = ropeKnots[i - 1];
var dist = knot.simpleDistanceFrom(prevKnot);
if (dist > 1) {
var v2 = knot.normalisedVectorTo(prevKnot);
knot.addV2(v2);
if (i == ropeKnots.length - 1) {
// is tail
var copy = Point.copy(knot);
tailVisited.add(copy);
}
}
}
}
}
}
print(tailVisited.length);
}