aboutsummaryrefslogtreecommitdiff
path: root/2025/src/day04.cpp
blob: 295ed756dc4ac07c80e8bd31c24624835273c7b8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <filesystem>
#include <fstream>
#include <iostream>
#include <set>
#include <string>
#include <tuple>

using namespace std;

namespace {

using Pos = tuple<size_t, size_t>;

set<Pos>
read_file(const filesystem::path& filename)
{
	ifstream file{ filename };
	set<Pos> 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<Pos>
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<Pos>& 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<Pos>& grid)
{
	long count = 0;
	for ( const auto pos: grid ) {
		if ( is_accessable(grid, pos) ) {
			++count;
		}
	}
	cout << "Part 1: " << count << '\n';
}

void
part2(set<Pos> grid)
{
	auto old_size = grid.size();
	while ( true ) {
		set<Pos> 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);
}