Skip to content

Instantly share code, notes, and snippets.

@johngian
Created December 5, 2021 09:56
Show Gist options
  • Save johngian/4e5316d39f1e109a3971c9e98f55508b to your computer and use it in GitHub Desktop.
Save johngian/4e5316d39f1e109a3971c9e98f55508b to your computer and use it in GitHub Desktop.
Advent of code 2021 - day 2 - solution
#include <iostream>
#include <cmath>
#include <map>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#include <day2.hpp>
namespace day2
{
std::string solution_part1(std::istream &std_input)
{
std::string line;
std::vector<std::string> commandLine;
std::map<std::string, int> commands;
commands["forward"] = 0;
commands["down"] = 0;
commands["up"] = 0;
while (std::getline(std_input, line))
{
boost::split(commandLine, line, boost::algorithm::is_space());
commands[commandLine[0]] += std::stoi(commandLine[1]);
}
return std::to_string(commands["forward"] * std::abs(commands["down"] - commands["up"]));
}
std::string solution_part2(std::istream &std_input)
{
std::string line;
std::vector<std::string> commandLine;
int horizontal = 0, aim = 0, depth = 0;
int value;
std::string move;
while (std::getline(std_input, line))
{
boost::split(commandLine, line, boost::algorithm::is_space());
move = commandLine[0];
value = std::stoi(commandLine[1]);
if (move == "up")
{
aim -= value;
}
else if (move == "down")
{
aim += value;
}
else if (move == "forward")
{
horizontal += value;
depth += aim * value;
}
}
return std::to_string(depth * horizontal);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment