Add day 2 of 2021's puzzles.

This commit is contained in:
2021-12-02 06:57:48 +00:00
parent 51cec3ea26
commit d9e1d2cf89
2 changed files with 67 additions and 0 deletions

32
2021/puzzle-02-01.cc Normal file
View File

@@ -0,0 +1,32 @@
//
// Created by Matthew Gretton-Dann on 02/12/2021.
//
#include <string>
#include <iostream>
int main()
{
using namespace std::string_literals;
static const auto fwd{"forward "s};
static const auto down{"down "s};
static const auto up{"up "s};
std::string line;
unsigned long horiz{0};
unsigned long depth{0};
while (std::getline(std::cin, line)) {
if (line.size() > fwd.size() && line.substr(0,fwd.size()) == fwd) {
horiz += std::stoul(line.substr(fwd.size()));
}
if (line.size() > down.size() && line.substr(0,down.size()) == down) {
depth += std::stoul(line.substr(down.size()));
}
if (line.size() > up.size() && line.substr(0,up.size()) == up) {
depth -= std::stoul(line.substr(up.size()));
}
}
std::cout << "Distance * depth: " << horiz << " * " << depth << " = " << horiz * depth << '\n';
}

35
2021/puzzle-02-02.cc Normal file
View File

@@ -0,0 +1,35 @@
//
// Created by Matthew Gretton-Dann on 02/12/2021.
//
#include <string>
#include <iostream>
int main()
{
using namespace std::string_literals;
static const auto fwd{"forward "s};
static const auto down{"down "s};
static const auto up{"up "s};
std::string line;
unsigned long horiz{0};
unsigned long depth{0};
unsigned long aim{0};
while (std::getline(std::cin, line)) {
if (line.size() > fwd.size() && line.substr(0,fwd.size()) == fwd) {
auto dist{std::stoul(line.substr(fwd.size()))};
horiz += dist;
depth += aim * dist;
}
if (line.size() > down.size() && line.substr(0,down.size()) == down) {
aim += std::stoul(line.substr(down.size()));
}
if (line.size() > up.size() && line.substr(0,up.size()) == up) {
aim -= std::stoul(line.substr(up.size()));
}
}
std::cout << "Distance * depth: " << horiz << " * " << depth << " = " << horiz * depth << '\n';
}