summaryrefslogtreecommitdiffstats
path: root/day02/solution.cpp
blob: 23304c12c5a49b95af60d70ae083df9b60ab4c03 (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
#include <bits/stdc++.h>

namespace views = std::views;
namespace ranges = std::ranges;

auto parse_input(std::istream& is) {
    const std::string input = {
        std::istreambuf_iterator<char>(is),
        std::istreambuf_iterator<char>()
    };

    auto char_range_to_int = [](auto&& r) {
        auto&& s = ranges::to<std::string>(r);
        return std::stoll(s);
    };
    auto lines = views::split(input, ',')
            | views::filter([](auto line) { return not line.empty(); });

    std::vector<std::pair<long, long>> _ranges;
    for (auto const line : lines) {
        auto numbers = line
            | views::split('-')
            | views::transform(char_range_to_int);
        _ranges.emplace_back(*numbers.begin(), *std::next(numbers.begin()));
    }
    return _ranges;
}


void part1(auto const& input) {
    // Write first part solution here
    long answer = 0;

    for (auto [begin, end] : input) {
        for (auto i = begin; i <= end; ++i) {
            std::string s{std::format("{}", i)};
            size_t half_size = s.size() / 2;
            std::string_view sl{s.begin(), s.begin() + half_size};
            std::string_view sr{s.begin() + half_size, s.end()};
            if (sl == sr) {
                answer += i;
            }
        }
    }

    std::println("{}", answer);
}

void part2(auto const& input) {
    // Write second part solution here
    long answer = 0;

    for (auto [begin, end] : input) {
        for (auto i = begin; i <= end; ++i) {
            std::stringstream ss;
            ss << i;
            std::string_view s{ss.str()};
            for (int chunk_size = 1; chunk_size <= s.size() / 2; ++chunk_size) {
                if (s.size() % chunk_size != 0) {
                    continue;
                }
                auto chunks = s | views::chunk(chunk_size);
                auto value = *chunks.begin();
                if (ranges::all_of(chunks, [value](auto&& chunk) {
                    return ranges::equal(chunk, value);
                })) {
                    answer += i;
                    break;
                }
            }
        }
    }

    std::println("{}", answer);

}

int main() {
    auto const input = parse_input(std::cin);

    part1(input);
    part2(input);

    return 0;
}