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
|
#include <iostream>
#include <fstream>
#include <vector>
using Schematic = std::vector<std::string>;
bool check(const Schematic& schematic, int x, int y)
{
return x >= 0 and y >= 0 and x < schematic.size() and y < schematic[x].size()
and schematic[x][y] != '.' and not std::isdigit(schematic[x][y]);
}
bool check_adj(const Schematic& schematic, int x, int y)
{
return check(schematic, x - 1, y - 1)
or check(schematic, x, y - 1)
or check(schematic, x + 1, y - 1)
or check(schematic, x - 1, y)
or check(schematic, x + 1, y);
}
int find_nums(const Schematic& schematic)
{
int sum{};
for (int x = 0; x < schematic.size(); ++x)
{
const std::string& line = schematic[x];
int cur{};
bool adj{ false };
for (int y = 0; y < line.size(); ++y)
{
if (std::isdigit(line[y]))
{
cur = 10 * cur + (line[y] - '0');
adj = adj or check_adj(schematic, x, y);
}
else
{
if (cur > 0)
{
adj = adj or check(schematic, x - 1, y)
or check(schematic, x, y)
or check(schematic, x + 1, y);
sum += adj ? cur : 0;
}
cur = 0;
adj = false;
}
}
}
return sum;
}
int main(void)
{
int answer{};
Schematic schematic{};
std::ifstream input{ "resources/input.txt" };
if (input.is_open())
{
std::string line;
while (not std::getline(input,line).eof())
{
line.push_back('.');
schematic.push_back(std::move(line));
}
}
input.close();
answer = find_nums(schematic);
std::cout << answer << std::endl;
return 0;
}
|