diff --git a/input/2025-4.sample.txt b/input/2025-4.sample.txt new file mode 100644 index 0000000..8209399 --- /dev/null +++ b/input/2025-4.sample.txt @@ -0,0 +1,10 @@ +..@@.@@@@. +@@@.@.@.@@ +@@@@@.@.@@ +@.@@@@..@. +@@.@@@@.@@ +.@@@@@@@.@ +.@.@.@.@@@ +@.@@@.@@@@ +.@@@@@@@@. +@.@.@@@.@. diff --git a/src/day4.cpp b/src/day4.cpp new file mode 100644 index 0000000..c760c10 --- /dev/null +++ b/src/day4.cpp @@ -0,0 +1,97 @@ +// :autocmd BufWritePost *.cpp :silent exec "!./build 4" +#include +#include +#include +#include +#include + +// investigate nob.h and c macros, macroify derive(eq, hash, ...) +struct Roll { + int64_t row; + int64_t col; +}; + +bool operator==(const Roll &lhs, const Roll &rhs) { + return lhs.row == rhs.row && lhs.col == rhs.col; +} + +using Grid = std::vector; +using Rolls = std::vector; + +int64_t part_1(const Grid &grid, const Rolls &rolls); +int64_t part_2(Grid, std::vector rolls); + +int main() { + std::ifstream file{"input/2025-4.txt"}; + std::string line; + Roll roll_iter{}; + std::vector rolls; + Grid grid; + while (std::getline(file, line)) { + grid.push_back(line); + for (char c : line) { + if (c == '@') { + Roll local_copy = roll_iter; + rolls.push_back(local_copy); + } + roll_iter.col += 1; + } + roll_iter.row += 1; + roll_iter.col = 0; + } + std::cout << "Part 1: " << part_1(grid, rolls) << std::endl; + std::cout << "Part 2: " << part_2(grid, rolls) << std::endl; +} + +void is_roll_helper(size_t row, size_t col, const Grid &grid, short &ans) { + if (row >= 0 && row < grid.size() && col >= 0 && col < grid[row].size() && + grid[row][col] == '@') { + ans += 1; + } +} + +short num_neighbors(const Grid &grid, const Roll &roll) { + short ans{0}; + is_roll_helper(roll.row - 1, roll.col - 1, grid, ans); + is_roll_helper(roll.row - 1, roll.col, grid, ans); + is_roll_helper(roll.row - 1, roll.col + 1, grid, ans); + is_roll_helper(roll.row, roll.col - 1, grid, ans); + is_roll_helper(roll.row, roll.col + 1, grid, ans); + is_roll_helper(roll.row + 1, roll.col - 1, grid, ans); + is_roll_helper(roll.row + 1, roll.col, grid, ans); + is_roll_helper(roll.row + 1, roll.col + 1, grid, ans); + return ans; +} + +int64_t part_1(const Grid &grid, const Rolls &rolls) { + int64_t ans{0}; + for (auto roll : rolls) { + auto cnt{num_neighbors(grid, roll)}; + if (cnt < 4) { + ans += 1; + } + } + return ans; +} + +int64_t part_2(Grid grid, Rolls rolls) { + int64_t last_roll_cnt = INT64_MAX; + int64_t ans{0}; + Rolls to_delete{}; + do { + to_delete.clear(); + for (auto roll : rolls) { + auto cnt{num_neighbors(grid, roll)}; + if (cnt < 4) { + ans += 1; + to_delete.emplace_back(roll); + } + } + + for (auto roll : to_delete) { + std::erase(rolls, roll); + grid[roll.row][roll.col] = '.'; + } + } while (to_delete.size() != 0); + return ans; +}