summaryrefslogtreecommitdiff
path: root/2023/03/src/part2.cpp
blob: 16e9678be412ffb4b87d68e3ce95ee233ba206af (plain) (blame)
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
#include <fstream>
#include <iostream>
#include <map>
#include <vector>
#include <cmath>

using Schematic = std::vector<std::string>;
using Gears = std::map<std::pair<int,int>,std::vector<int>>;

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<int,int> key{ x, y };
        if (not gears.count(key))
        {
            gears.insert({key, std::vector<int>{}});
        }
        gears[key].push_back(num);
    }
}

void check_gears(const Schematic& schematic, Gears& gears, int num, int x, int y)
{
    int len = 1 + static_cast<int>(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;
}