-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay11.cpp
More file actions
89 lines (70 loc) · 2.52 KB
/
Day11.cpp
File metadata and controls
89 lines (70 loc) · 2.52 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
80
81
82
83
84
85
86
87
88
89
#include "Day11.h"
string Day11::ParseInput()
{
ifstream input("Input/Day11.txt");
if (input.fail())
{
cout << "Failed to open inputfile." << endl;
return "";
}
string line;
getline(input, line);
return line;
}
Helpers::Point Day11::FollowPath(const string& input)
{
// Create a vector of directions to follow
vector<Helpers::Point> directionsToFollow = vector<Helpers::Point>();
for (const string& direction : Helpers::Split(input, ','))
directionsToFollow.push_back(_directions[direction]);
// Follow that path
Helpers::Point origin = Helpers::Point(0, 0);
for (size_t i = 0; i < directionsToFollow.size(); ++i)
{
origin += directionsToFollow[i];
// optimization: if only part 1 is run, don't do the calculations for part 2
if (_part1)
continue;
// Part 2: calculate the furthest steps away
vector<Helpers::Point> route = vector<Helpers::Point>();
CalculateShortestRoute(route, origin, Helpers::Point(0, 0));
// Update the furthest steps away if this one was further
if (route.size() > _furthestStepsAway)
_furthestStepsAway = route.size();
}
return origin;
}
void Day11::CalculateShortestRoute(vector<Helpers::Point>& route, const Helpers::Point& destination, Helpers::Point currentPosition)
{
// Start step as the total needed difference (how much X and how much Y still has to be moved to reach the destination)
Helpers::Point step = destination - currentPosition;
// Calculate which direction gets most result in 1 step
step.X = (step.X == 0) ? 0 : destination.X / abs(destination.X);
step.Y = (step.Y == 0) ? 0 : destination.Y / abs(destination.Y);
// Add the step to the path
route.push_back(step);
// Update the current position
currentPosition += step;
// Check if the destination has been reached
if (currentPosition.X == destination.X && currentPosition.Y == destination.Y)
return;
// Calculate the next step of the route if the destination hasn't been reached yet
CalculateShortestRoute(route, destination, currentPosition);
}
void Day11::Part1()
{
_part1 = true;
// Follow the path to determine the destination
Helpers::Point destination = FollowPath(ParseInput());
// Calculate the shortest route to the destination
vector<Helpers::Point> route = vector<Helpers::Point>();
CalculateShortestRoute(route, destination, Helpers::Point(0, 0));
cout << "Day 11 Part 1 answer: " << route.size() << endl;
}
void Day11::Part2()
{
_part1 = false;
// Follow the path
Helpers::Point destination = FollowPath(ParseInput());
cout << "Day 11 Part 2 answer: " << _furthestStepsAway << endl;
}