From 68de78a5856f21ce40e435615904aae996c2e856 Mon Sep 17 00:00:00 2001 From: Eric Mertens Date: Sun, 4 Dec 2022 10:30:01 -0800 Subject: [PATCH] 2022-03 --- 2022/03.cpp | 92 +++++++++++++++++++++++++++++++++++++++++++++ 2022/CMakeLists.txt | 3 ++ 2 files changed, 95 insertions(+) create mode 100644 2022/03.cpp diff --git a/2022/03.cpp b/2022/03.cpp new file mode 100644 index 0000000..752d7a9 --- /dev/null +++ b/2022/03.cpp @@ -0,0 +1,92 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +namespace { + +auto Parse(std::istream & in) -> std::vector +{ + std::vector result; + std::string line; + while (std::getline(in, line)) { + result.emplace_back(std::move(line)); + } + return result; +} + +auto Priority(char const c) -> std::int64_t +{ + return c < 'a' ? c-'A'+27 : c-'a'+1; +} + +auto Intersect(std::string const& a, std::string const& b) { + std::string common; + std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), + std::back_inserter(common)); + return common; +} + +auto Part1(std::vector const& input) -> std::int64_t +{ + std::int64_t n {0}; + for (auto const& line : input) { + auto m = line.size() / 2; + + auto elf1 {line.substr(0, m)}; + std::sort(elf1.begin(), elf1.end()); + + auto elf2 {line.substr(m)}; + std::sort(elf2.begin(), elf2.end()); + + n += Priority(Intersect(elf1, elf2).at(0)); + } + return n; +} + +auto Part2(std::vector input) -> std::int64_t +{ + std::int64_t n {0}; + + for (auto & line : input) { + std::sort(line.begin(), line.end()); + } + + for (std::size_t i = 0; i + 2 < input.size(); i += 3) { + n += Priority(Intersect(Intersect(input[i], input[i+1]), input[i+2]).at(0)); + } + return n; +} + +} // namespace + +TEST_SUITE("2022-03 examples") { + TEST_CASE("example") { + std::istringstream in { + "vJrwpWtwJgWrhcsFMMfFFhFp\n" + "jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL\n" + "PmmdzqPrVvPwwTWBwg\n" + "wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn\n" + "ttgJtRGJQctTZtZT\n" + "CrZsJsPPZsGzwwsLwLmpwMDw\n"}; + auto input = Parse(in); + CHECK(Part1(input) == 157); + CHECK(Part2(std::move(input)) == 70); + } +} + +auto main(int argc, char** argv) -> int { + auto input = Parse(*aocpp::Startup(argc, argv)); + std::cout << "Part 1: " << Part1(input) << std::endl; + std::cout << "Part 2: " << Part2(std::move(input)) << std::endl; +} diff --git a/2022/CMakeLists.txt b/2022/CMakeLists.txt index 96e23bb..d7366a4 100644 --- a/2022/CMakeLists.txt +++ b/2022/CMakeLists.txt @@ -1,5 +1,8 @@ add_executable(2022_01 01.cpp) target_link_libraries(2022_01 aocpp) +add_executable(2022_03 03.cpp) +target_link_libraries(2022_03 aocpp) + add_executable(2022_04 04.cpp) target_link_libraries(2022_04 aocpp)