diff --git a/src/day7.cpp b/src/day7.cpp index 26a1628..83f366c 100644 --- a/src/day7.cpp +++ b/src/day7.cpp @@ -1,11 +1,14 @@ // :autocmd BufWritePost *.cpp :silent exec "!script/async-build 7" +#include #include #include #include #include #include +#include #include #include +#include #include using Grid = std::vector; @@ -35,14 +38,12 @@ char at_loc(const Grid &grid, size_t row, size_t col) { } Location find_start(const Grid &grid) { - for (size_t row{0}; row < grid.size(); ++row) { - for (size_t col{0}; col < grid[row].length(); ++col) { - if (grid[row][col] == 'S') { - return {row, col}; - } - } + const auto col{grid[0].find_first_of('S')}; + if (col != std::string::npos) { + return {0, col}; + } else { + std::unreachable(); } - throw "unreachable"; } uint64_t part_1(const Grid &grid) { @@ -69,23 +70,18 @@ uint64_t part_1(const Grid &grid) { void insert_or_increment(std::map &cols, size_t col, uint64_t value) { - auto iter{cols.find(col)}; - if (iter == cols.end()) { - cols.insert({col, value}); - } else { - - iter->second += value; - } + cols.insert({col, 0}).first->second += value; } uint64_t part_2(const Grid &grid) { Location start = find_start(grid); const auto [start_row, start_col]{start}; - std::map cols; - cols.insert({start_col, 1}); - for (size_t row{start_row}; row < grid.size(); ++row) { + using namespace std::ranges::views; + auto view = std::ranges::iota_view{start_row, grid.size()}; + std::map starting_cols{{start_col, 1}}; + auto cols = std::accumulate(view.begin(), view.end(), starting_cols, [&grid](auto acc, auto row){ std::map next_cols; - for (auto [col, cnt] : cols) { + for (auto [col, cnt] : acc) { if (at_loc(grid, row, col) == '^') { insert_or_increment(next_cols, col - 1, cnt); insert_or_increment(next_cols, col + 1, cnt); @@ -93,8 +89,8 @@ uint64_t part_2(const Grid &grid) { insert_or_increment(next_cols, col, cnt); } } - cols = std::move(next_cols); - } + return next_cols; + }); return std::accumulate( cols.begin(), cols.end(), 0ull, [](const uint64_t acc, const auto &entry) { return acc + entry.second; });