@@ -7,7 +7,7 @@ const Map = std.AutoHashMap;
7
7
const String = []u8 ;
8
8
const Matrix = List (String );
9
9
const Vec2 = struct { x : i32 , y : i32 };
10
- const Guard = struct { pos : Vec2 , dir : Vec2 };
10
+ const State = struct { pos : Vec2 , dir : Vec2 };
11
11
const Walk = struct { visited : Set (Vec2 ), loops : bool };
12
12
13
13
fn Set (comptime T : type ) type {
@@ -30,7 +30,7 @@ fn turnRight(dir: Vec2) Vec2 {
30
30
return .{ .x = - dir .y , .y = dir .x };
31
31
}
32
32
33
- fn step (guard : Guard ) Guard {
33
+ fn step (guard : State ) State {
34
34
return .{ .pos = vecAdd (guard .pos , guard .dir ), .dir = guard .dir };
35
35
}
36
36
@@ -52,7 +52,7 @@ fn parseDirection(c: u8) ?Vec2 {
52
52
};
53
53
}
54
54
55
- fn findStart (matrix : Matrix ) Guard {
55
+ fn findStart (matrix : Matrix ) State {
56
56
for (0.. height (matrix )) | y | {
57
57
for (0.. width (matrix )) | x | {
58
58
const dir = parseDirection (matrix .items [y ][x ]);
@@ -64,21 +64,18 @@ fn findStart(matrix: Matrix) Guard {
64
64
std .debug .panic ("Could not find start" , .{});
65
65
}
66
66
67
- fn walkFrom (start : Guard , matrix : Matrix , extraObstacle : ? Vec2 ) ! Walk {
68
- var visited = Set (Vec2 ).init (allocator );
69
- var visitedGuards = Set (Guard ).init (allocator );
67
+ fn walkFrom (start : State , matrix : Matrix , extraObstacle : ? Vec2 ) ! Walk {
68
+ var visitedPositions = Set (Vec2 ).init (allocator );
69
+ var visitedStates = Set (State ).init (allocator );
70
+ defer visitedStates .deinit ();
70
71
var guard = start ;
71
72
72
- defer {
73
- visitedGuards .deinit ();
74
- }
75
-
76
73
while (inBounds (guard .pos , matrix )) {
77
- if (visitedGuards .contains (guard )) {
78
- return .{ .visited = visited , .loops = true };
74
+ if (visitedStates .contains (guard )) {
75
+ return .{ .visited = visitedPositions , .loops = true };
79
76
}
80
- try visited .put (guard .pos , {});
81
- try visitedGuards .put (guard , {});
77
+ try visitedPositions .put (guard .pos , {});
78
+ try visitedStates .put (guard , {});
82
79
const next = step (guard );
83
80
if (inBounds (next .pos , matrix ) and ((extraObstacle != null and std .meta .eql (next .pos , extraObstacle .? )) or get (next .pos , matrix ) == '#' )) {
84
81
guard .dir = turnRight (guard .dir );
@@ -87,7 +84,7 @@ fn walkFrom(start: Guard, matrix: Matrix, extraObstacle: ?Vec2) !Walk {
87
84
}
88
85
}
89
86
90
- return .{ .visited = visited , .loops = false };
87
+ return .{ .visited = visitedPositions , .loops = false };
91
88
}
92
89
93
90
pub fn main () ! u8 {
0 commit comments