-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday3.h
62 lines (57 loc) · 1.44 KB
/
day3.h
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
#include <fstream>
#include <map>
#include <set>
namespace {
using namespace std;
using Vector = pair<int, int>;
auto trace = [](ifstream& input, auto f) {
Vector point = { 0, 0 };
int steps = 0;
do {
char direction;
int count;
input >> direction >> count;
while (count--) {
if (direction == 'U')
point.first--;
else if (direction == 'L')
point.second--;
else if (direction == 'D')
point.first++;
else if (direction == 'R')
point.second++;
f(point, ++steps);
}
} while (input.peek() == ',' && input.ignore());
};
int part1(ifstream input) {
set<Vector> first;
trace(input, [&](Vector point, int) {
first.insert(point);
});
int minimum = INT_MAX;
trace(input, [&](Vector point, int) {
if (first.count(point)) {
int distance = abs(point.first) + abs(point.second);
if (distance < minimum)
minimum = distance;
}
});
return minimum;
}
int part2(ifstream input) {
map<Vector, int> first;
trace(input, [&](Vector point, int steps) {
first[point] = steps;
});
int minimum = INT_MAX;
trace(input, [&](Vector point, int steps) {
if (auto it = first.find(point); it != first.end()) {
int combined = it->second + steps;
if (combined < minimum)
minimum = combined;
}
});
return minimum;
}
}