From acb278e7a61b13d14767e3a84c75d4f9f0ca6e7a Mon Sep 17 00:00:00 2001 From: Thomas Schmucker Date: Thu, 4 Dec 2025 12:56:24 +0100 Subject: aoc 2025, day 4 --- 2025/src/day04.cpp | 106 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 2025/src/day04.cpp (limited to '2025/src/day04.cpp') diff --git a/2025/src/day04.cpp b/2025/src/day04.cpp new file mode 100644 index 0000000..295ed75 --- /dev/null +++ b/2025/src/day04.cpp @@ -0,0 +1,106 @@ +#include +#include +#include +#include +#include +#include + +using namespace std; + +namespace { + +using Pos = tuple; + +set +read_file(const filesystem::path& filename) +{ + ifstream file{ filename }; + set grid; + + size_t row = 0; + for ( string line; getline(file, line); ) { + for ( size_t col = 0; col != line.length(); ++col ) { + if ( line[col] == '@' ) { + grid.emplace(col, row); + } + } + ++row; + } + + return grid; +} + +set +get_neighbours(const Pos& pos) +{ + auto [col, row] = pos; + + return { + Pos{ col - 1, row }, + Pos{ col - 1, row - 1 }, + Pos{ col, row - 1 }, + Pos{ col + 1, row - 1 }, + Pos{ col + 1, row }, + Pos{ col + 1, row + 1 }, + Pos{ col, row + 1 }, + Pos{ col - 1, row + 1 }, + }; +} + +bool +is_accessable(const set& grid, const Pos& pos) +{ + long nneighbours = 0; + for ( const auto neighbour: get_neighbours(pos) ) { + if ( grid.contains(neighbour) ) { + ++nneighbours; + } + } + return nneighbours < 4; +} + +void +part1(const set& grid) +{ + long count = 0; + for ( const auto pos: grid ) { + if ( is_accessable(grid, pos) ) { + ++count; + } + } + cout << "Part 1: " << count << '\n'; +} + +void +part2(set grid) +{ + auto old_size = grid.size(); + while ( true ) { + set remove; + + for ( const auto& pos: grid ) { + if ( is_accessable(grid, pos) ) { + remove.insert(pos); + } + } + + if ( remove.empty() ) { + break; + } + + for ( const auto& pos: remove ) { + grid.erase(pos); + } + } + cout << "Part 2: " << old_size - grid.size() << '\n'; +} + +} // namespace + +int +main() +{ + auto grid = read_file("data/day04.txt"); + part1(grid); + part2(grid); +} -- cgit v1.3