-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06-Guard-Gallivant.cpp
More file actions
79 lines (63 loc) · 2.02 KB
/
06-Guard-Gallivant.cpp
File metadata and controls
79 lines (63 loc) · 2.02 KB
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
// Copyright (C) 2024 Joe Baker (JoeBlakeB)
// Advent of Code 2024 - Day 6: Guard Gallivant
// Usage:
// scripts/cppRun.sh 2024/06-Guard-Gallivant.cpp < 2024/inputs/06.txt
#include <cstdint>
#include <iostream>
#include <string>
#include <vector>
#include "../Utils/Grid.cpp"
using namespace std;
CharGrid simulateGuard(CharGrid map) {
Coordinate guard = map.findFirst('^');
Direction direction = UP;
while (map.contains(guard)) {
bool containsNext = map.contains(guard(direction));
if (!containsNext || map[guard(direction)] != '#') {
map[guard] = 'X';
guard = guard(direction);
} else {
direction = turnClockwise(direction);
}
}
return map;
}
bool simulateGuardCanLeave(CharGrid map) {
Coordinate guard = map.findFirst('^');
Direction direction = UP;
while (map.contains(guard)) {
bool containsNext = map.contains(guard(direction));
if (!containsNext || map[guard(direction)] != '#') {
int8_t visited = 0;
if (map[guard] > 'a' && map[guard] <= 'a'+0xF) {
visited = map[guard] - 'a';
if (visited & (1 << direction)) {
return true;
}
}
visited |= (1 << direction);
map[guard] = 'a' + visited;
guard = guard(direction);
} else {
direction = turnClockwise(direction);
}
}
return false;
}
int howManyObstaclesCanCauseLoop(const CharGrid& map) {
int count = 0;
map.forEach([&count, map](Coordinate coordinate) {
if (map[coordinate] == '.') {
CharGrid newMap = map;
newMap[coordinate] = '#';
count += simulateGuardCanLeave(newMap);
}
});
return count;
}
int main() {
CharGrid map = {cin};
cout << "Positions until guard leaves: " << simulateGuard(map).count('X') << endl;
cout << "Positions the obstruction can go: " << howManyObstaclesCanCauseLoop(map) << endl;
return 0;
}