std::accumulate all the nonsense
This commit is contained in:
parent
4df6ee4533
commit
787476b47c
36
src/day7.cpp
36
src/day7.cpp
@ -1,11 +1,14 @@
|
||||
// :autocmd BufWritePost *.cpp :silent exec "!script/async-build 7"
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <numeric>
|
||||
#include <ranges>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
using Grid = std::vector<std::string>;
|
||||
@ -35,15 +38,13 @@ 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) {
|
||||
uint64_t ans{0};
|
||||
@ -69,23 +70,18 @@ uint64_t part_1(const Grid &grid) {
|
||||
|
||||
void insert_or_increment(std::map<size_t, uint64_t> &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<size_t, uint64_t> 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<size_t, uint64_t> starting_cols{{start_col, 1}};
|
||||
auto cols = std::accumulate(view.begin(), view.end(), starting_cols, [&grid](auto acc, auto row){
|
||||
std::map<size_t, uint64_t> 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; });
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user