From d9e1d2cf89912391c2f678fc78ea2d9203205201 Mon Sep 17 00:00:00 2001 From: Matthew Gretton-Dann Date: Thu, 2 Dec 2021 06:57:48 +0000 Subject: [PATCH] Add day 2 of 2021's puzzles. --- 2021/puzzle-02-01.cc | 32 ++++++++++++++++++++++++++++++++ 2021/puzzle-02-02.cc | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 2021/puzzle-02-01.cc create mode 100644 2021/puzzle-02-02.cc diff --git a/2021/puzzle-02-01.cc b/2021/puzzle-02-01.cc new file mode 100644 index 0000000..acb4a51 --- /dev/null +++ b/2021/puzzle-02-01.cc @@ -0,0 +1,32 @@ +// +// Created by Matthew Gretton-Dann on 02/12/2021. +// + +#include +#include + +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'; +} \ No newline at end of file diff --git a/2021/puzzle-02-02.cc b/2021/puzzle-02-02.cc new file mode 100644 index 0000000..91ee5dc --- /dev/null +++ b/2021/puzzle-02-02.cc @@ -0,0 +1,35 @@ +// +// Created by Matthew Gretton-Dann on 02/12/2021. +// + +#include +#include + +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'; +} \ No newline at end of file