-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday2.cpp
64 lines (55 loc) · 1.58 KB
/
day2.cpp
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
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
using Command = pair<string, int>;
using Commands = vector<Command>;
long part1(Commands& commands)
{
int position = 0;
int depth = 0;
for (auto& command : commands) {
if (command.first == "forward") {
position = position + command.second;
} else if (command.first == "down") {
depth = depth + command.second;
} else if (command.first == "up") {
depth = depth - command.second;
}
}
return position * depth;
}
long part2(Commands& commands)
{
int position = 0;
int aim = 0;
long depth = 0;
for (auto& command : commands) {
if (command.first == "forward") {
position = position + command.second;
depth = depth + (aim * command.second);
} else if (command.first == "down") {
aim = aim + command.second;
} else if (command.first == "up") {
aim = aim - command.second;
}
}
return position * depth;
}
int main(int argc, char* argv[])
{
ifstream input;
input.open(argc < 2 ? "day2.txt" : argv[1], ifstream::in);
Commands commands;
string direction;
int distance;
while (input.good()) {
input >> direction >> distance;
if (!input.good()) break; // account for an incomplete input, e.g. a blank line
Command command(direction, distance);
commands.push_back(command);
}
cout << "Part 1: " << part1(commands) << "\n";
cout << "Part 2: " << part2(commands) << "\n";
}