This commit is contained in:
Eric Mertens 2022-12-04 10:30:01 -08:00
parent dc37b7b450
commit 68de78a585
2 changed files with 95 additions and 0 deletions

92
2022/03.cpp Normal file
View File

@ -0,0 +1,92 @@
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <sstream>
#include <stdexcept>
#include <string>
#include <tuple>
#include <vector>
#include <string_view>
#include <doctest.h>
#include <aocpp/Startup.hpp>
namespace {
auto Parse(std::istream & in) -> std::vector<std::string>
{
std::vector<std::string> 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<std::string> 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<std::string> 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;
}

View File

@ -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)