From d3999e2e8fd03c0592e9c132ef0559b019fedc25 Mon Sep 17 00:00:00 2001 From: Matthew Gretton-Dann Date: Tue, 20 Dec 2022 21:31:31 +0000 Subject: [PATCH] Add solutions for 2018 day 5 --- 2018/puzzle-05-01.cc | 43 ++++++++++++++++++++++++++++++++++ 2018/puzzle-05-02.cc | 56 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 2018/puzzle-05-01.cc create mode 100644 2018/puzzle-05-02.cc diff --git a/2018/puzzle-05-01.cc b/2018/puzzle-05-01.cc new file mode 100644 index 0000000..dfb4fd5 --- /dev/null +++ b/2018/puzzle-05-01.cc @@ -0,0 +1,43 @@ +// +// Created by Matthew Gretton-Dann on 01/12/2022. +// + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using UInt = std::uint64_t; + +using namespace std::string_literals; + +auto main() -> int +{ + std::string polymer; + + if (!std::getline(std::cin, polymer)) { + std::cout << "Unable to read line.\n"; + return EXIT_FAILURE; + } + + auto it{polymer.begin()}; + while ((it + 1) != polymer.end()) { + if (*it != *(it + 1) && (*it == std::tolower(*(it + 1)) || *it == std::toupper(*(it + 1)))) { + it = polymer.erase(it, it + 2); + if (it != polymer.begin()) { + --it; + } + } + else { + ++it; + } + } + std::cout << "Polymer: " << polymer << "\n"; + std::cout << "Length: " << polymer.size() << "\n"; + return EXIT_SUCCESS; +} diff --git a/2018/puzzle-05-02.cc b/2018/puzzle-05-02.cc new file mode 100644 index 0000000..ce43f91 --- /dev/null +++ b/2018/puzzle-05-02.cc @@ -0,0 +1,56 @@ +// +// Created by Matthew Gretton-Dann on 01/12/2022. +// + +#include +#include +#include +#include +#include +#include + +using UInt = std::uint64_t; + +using namespace std::string_literals; + +auto amend_polymer(std::string polymer, char remove) -> std::string +{ + auto it{std::remove_if(polymer.begin(), polymer.end(), + [remove](auto c) { return c == remove || (c == std::toupper(remove)); })}; + return {polymer.begin(), it}; +} + +auto react_polymer(std::string polymer) -> UInt +{ + auto it{polymer.begin()}; + while ((it + 1) != polymer.end()) { + if (*it != *(it + 1) && (*it == std::tolower(*(it + 1)) || *it == std::toupper(*(it + 1)))) { + it = polymer.erase(it, it + 2); + if (it != polymer.begin()) { + --it; + } + } + else { + ++it; + } + } + return polymer.size(); +} + +auto main() -> int +{ + std::string polymer; + + if (!std::getline(std::cin, polymer)) { + std::cout << "Unable to read line.\n"; + return EXIT_FAILURE; + } + + UInt min_length{polymer.size() + 1}; + for (char c{'a'}; c < 'z' + 1; ++c) { + std::string const poly2{amend_polymer(polymer, c)}; + min_length = std::min(min_length, react_polymer(poly2)); + } + std::cout << "Minimum length: " << min_length << "\n"; + return EXIT_SUCCESS; +}