summaryrefslogtreecommitdiff
path: root/2023/03/src/part2.cpp
diff options
context:
space:
mode:
Diffstat (limited to '2023/03/src/part2.cpp')
-rw-r--r--2023/03/src/part2.cpp97
1 files changed, 97 insertions, 0 deletions
diff --git a/2023/03/src/part2.cpp b/2023/03/src/part2.cpp
new file mode 100644
index 0000000..16e9678
--- /dev/null
+++ b/2023/03/src/part2.cpp
@@ -0,0 +1,97 @@
1#include <fstream>
2#include <iostream>
3#include <map>
4#include <vector>
5#include <cmath>
6
7using Schematic = std::vector<std::string>;
8using Gears = std::map<std::pair<int,int>,std::vector<int>>;
9
10void check(const Schematic& schematic, Gears& gears, int num, int x, int y)
11{
12 if (x >= 0 and y >= 0 and x < schematic.size()
13 and y < schematic[x].size() and schematic[x][y] == '*')
14 {
15 std::pair<int,int> key{ x, y };
16 if (not gears.count(key))
17 {
18 gears.insert({key, std::vector<int>{}});
19 }
20 gears[key].push_back(num);
21 }
22}
23
24void check_gears(const Schematic& schematic, Gears& gears, int num, int x, int y)
25{
26 int len = 1 + static_cast<int>(std::log10(num));
27 check(schematic, gears, num, x - 1, y - len - 1);
28 check(schematic, gears, num, x, y - len - 1);
29 check(schematic, gears, num, x + 1, y - len - 1);
30 for (int a = 1; a <= len; ++a)
31 {
32 check(schematic, gears, num, x - 1, y - a);
33 check(schematic, gears, num, x + 1, y - a);
34 }
35 check(schematic, gears, num, x - 1, y);
36 check(schematic, gears, num, x, y);
37 check(schematic, gears, num, x + 1, y);
38}
39
40Gears find_gears(const Schematic& schematic)
41{
42 Gears gears;
43
44 for (int x = 0; x < schematic.size(); ++x)
45 {
46 const std::string& line = schematic[x];
47
48 int cur{};
49
50 for (int y = 0; y < line.size(); ++y)
51 {
52 if (std::isdigit(line[y]))
53 {
54 cur = 10 * cur + (line[y] - '0');
55 }
56 else
57 {
58 if (cur > 0)
59 {
60 check_gears(schematic, gears, cur, x, y);
61 }
62 cur = 0;
63 }
64 }
65 }
66
67 return gears;
68}
69
70int main(void)
71{
72 int answer{};
73 Schematic schematic{};
74
75 std::ifstream input{ "resources/input.txt" };
76 if (input.is_open())
77 {
78 std::string line;
79 while (not std::getline(input,line).eof())
80 {
81 line.push_back('.');
82 schematic.push_back(std::move(line));
83 }
84 }
85 input.close();
86
87 Gears gears = find_gears(schematic);
88 for (const auto& [_, vals] : gears) {
89 if (vals.size() == 2)
90 {
91 answer += vals[0] * vals[1];
92 }
93 }
94
95 std::cout << answer << std::endl;
96 return 0;
97}