advent_of_code_2021/02/main.cpp
2021-12-02 10:54:48 +01:00

98 lines
2.3 KiB
C++

#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
enum Command {
Forward,
Down,
Up,
Undefined,
};
using CommandPair = std::pair<Command, int>;
std::vector<CommandPair> getCommands(const std::string &file_name) {
std::ifstream file(file_name);
std::vector<CommandPair> result{};
std::string tmp_command{};
int tmp_num{};
std::string str;
while (std::getline(file, str)) {
std::stringstream ss(str);
ss >> tmp_command;
ss >> tmp_num;
Command cmd = Undefined;
if (tmp_command == "forward") {
cmd = Forward;
} else if (tmp_command == "down") {
cmd = Down;
} else if (tmp_command == "up") {
cmd = Up;
}
if (cmd == Undefined) {
std::cerr << "Invalid input line: \"" << str << "\"" << std::endl;
return {};
}
result.emplace_back(cmd, tmp_num);
}
return result;
}
int part1(const std::vector<CommandPair> &commands) {
int x = 0;
int y = 0;
for (const auto &command : commands) {
switch (command.first) {
case Forward:
x += command.second;
break;
case Down:
y += command.second;
break;
case Up:
y -= command.second;
default:
break;
}
}
return x * y;
}
int part2(const std::vector<CommandPair> &commands) {
int x = 0;
int y = 0;
int aim = 0;
for (const auto &command : commands) {
switch (command.first) {
case Forward:
x += command.second;
y += aim * command.second;
break;
case Down:
aim += command.second;
break;
case Up:
aim -= command.second;
default:
break;
}
}
return x * y;
}
int main(int argc, char **argv) {
if (argc < 2) {
std::cerr << "You must provide input file!" << std::endl;
return 1;
}
auto commands = getCommands(argv[1]);
if (commands.empty()) {
return 1;
}
std::cout << "The resulting multiplication is \033[91;1m" << part1(commands)
<< "\033[0m." << std::endl;
std::cout << "The correct resulting multiplication is \033[91;1m"
<< part2(commands) << "\033[0m." << std::endl;
return 0;
}