aocpp/2022/08.cpp

80 lines
1.7 KiB
C++
Raw Normal View History

2023-01-23 08:55:37 -08:00
#include <algorithm>
#include <cstdint>
#include <functional>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
#include <doctest.h>
#include <aocpp/Grid.hpp>
#include <aocpp/Coord.hpp>
#include <aocpp/Startup.hpp>
using namespace aocpp;
namespace {
using Dir = Coord(*)(Coord);
Dir directions[4] {Up, Down, Left, Right};
auto Part1(Grid const& grid) -> std::int64_t
{
std::int64_t result {0};
2024-09-05 20:10:34 -07:00
for (auto [c, v] : grid) {
2023-01-23 08:55:37 -08:00
result += std::any_of(
std::begin(directions), std::end(directions),
[&](Dir const dir) {
for (auto x = dir(c); grid.contains(x); x = dir(x)) {
if (grid[x] >= v) { return false; }
}
return true;
});
2024-09-05 20:10:34 -07:00
}
2023-01-23 08:55:37 -08:00
return result;
}
auto Part2(Grid const& grid) -> std::int64_t
{
std::int64_t result {0};
2024-09-05 20:10:34 -07:00
for (auto [c, v] : grid) {
2023-01-23 08:55:37 -08:00
auto score = std::transform_reduce(
std::begin(directions), std::end(directions),
2023-01-31 08:58:42 -08:00
std::int64_t{1}, std::multiplies(), // product
2023-01-23 08:55:37 -08:00
[&](Dir const dir) {
std::int64_t count {0};
for (auto x = dir(c); grid.contains(x); x = dir(x)) {
count++;
if (grid[x] >= v) break;
}
return count;
});
if (result < score) result = score;
2024-09-05 20:10:34 -07:00
}
2023-01-23 08:55:37 -08:00
return result;
}
} // namespace
TEST_SUITE("2022-08 examples") {
TEST_CASE("example") {
std::istringstream in {
"30373\n"
"25512\n"
"65332\n"
"33549\n"
"35390\n"};
auto grid = aocpp::Grid::Parse(in);
CHECK(Part1(grid) == 21);
CHECK(Part2(grid) == 8);
}
}
2023-01-31 09:15:15 -08:00
auto Main(std::istream & in, std::ostream & out) -> void
2023-01-23 08:55:37 -08:00
{
2023-01-31 08:58:42 -08:00
auto const grid = Grid::Parse(in);
2023-01-31 09:15:15 -08:00
out << "Part 1: " << Part1(grid) << std::endl;
out << "Part 2: " << Part2(grid) << std::endl;
2023-01-23 08:55:37 -08:00
}