#include #include #include #include #include using Schematic = std::vector; using Gears = std::map,std::vector>; void check(const Schematic& schematic, Gears& gears, int num, int x, int y) { if (x >= 0 and y >= 0 and x < schematic.size() and y < schematic[x].size() and schematic[x][y] == '*') { std::pair key{ x, y }; if (not gears.count(key)) { gears.insert({key, std::vector{}}); } gears[key].push_back(num); } } void check_gears(const Schematic& schematic, Gears& gears, int num, int x, int y) { int len = 1 + static_cast(std::log10(num)); check(schematic, gears, num, x - 1, y - len - 1); check(schematic, gears, num, x, y - len - 1); check(schematic, gears, num, x + 1, y - len - 1); for (int a = 1; a <= len; ++a) { check(schematic, gears, num, x - 1, y - a); check(schematic, gears, num, x + 1, y - a); } check(schematic, gears, num, x - 1, y); check(schematic, gears, num, x, y); check(schematic, gears, num, x + 1, y); } Gears find_gears(const Schematic& schematic) { Gears gears; for (int x = 0; x < schematic.size(); ++x) { const std::string& line = schematic[x]; int cur{}; for (int y = 0; y < line.size(); ++y) { if (std::isdigit(line[y])) { cur = 10 * cur + (line[y] - '0'); } else { if (cur > 0) { check_gears(schematic, gears, cur, x, y); } cur = 0; } } } return gears; } 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(); Gears gears = find_gears(schematic); for (const auto& [_, vals] : gears) { if (vals.size() == 2) { answer += vals[0] * vals[1]; } } std::cout << answer << std::endl; return 0; }