This commit is contained in:
zvon 2021-12-02 10:54:48 +01:00
parent aaafa6daf3
commit 44e3ccb227
3 changed files with 1119 additions and 0 deletions

22
02/CMakeLists.txt Normal file
View File

@ -0,0 +1,22 @@
cmake_minimum_required(VERSION 3.10)
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED True)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
enable_language(CXX)
project(AoC02)
if(APPLE)
include_directories(/usr/local/include)
link_directories(/usr/local/lib)
endif()
if(WIN32)
add_executable(${CMAKE_PROJECT_NAME} WIN32)
else()
add_executable(${CMAKE_PROJECT_NAME})
endif()
target_sources(${CMAKE_PROJECT_NAME}
PRIVATE main.cpp
)

1000
02/input Normal file

File diff suppressed because it is too large Load Diff

97
02/main.cpp Normal file
View File

@ -0,0 +1,97 @@
#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;
}