aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--2025/src/day02.cpp115
1 files changed, 115 insertions, 0 deletions
diff --git a/2025/src/day02.cpp b/2025/src/day02.cpp
new file mode 100644
index 0000000..1d17cd9
--- /dev/null
+++ b/2025/src/day02.cpp
@@ -0,0 +1,115 @@
1#include <filesystem>
2#include <fstream>
3#include <iostream>
4#include <ranges>
5#include <sstream>
6#include <string>
7#include <vector>
8
9using namespace std;
10
11namespace {
12
13vector<string>
14split(const string& line, char sep)
15{
16 istringstream strm{ line };
17 vector<string> parts;
18
19 for ( string part; getline(strm, part, sep); ) {
20 parts.emplace_back(part);
21 }
22 return parts;
23}
24
25vector<tuple<long, long>>
26read_file(const filesystem::path& filename)
27{
28 ifstream file{ filename };
29 string line;
30 getline(file, line);
31
32 vector<tuple<long, long>> ranges;
33 for ( const auto& part: split(line, ',') ) {
34 const auto range = split(part, '-');
35 ranges.emplace_back(stol(range.at(0)), stol(range.at(1)));
36 }
37 return ranges;
38}
39
40long
41accumulate_invalids(const vector<tuple<long, long>>& ranges, const function<bool(long)>& is_invalid)
42{
43 long sum = 0;
44 for ( const auto [from, to]: ranges ) {
45 for ( auto i = from; i <= to; ++i ) {
46 if ( is_invalid(i) ) {
47 sum += i;
48 }
49 }
50 }
51 return sum;
52}
53
54void
55part1(const vector<tuple<long, long>>& ranges)
56{
57 auto is_invalid = [](long num) {
58 const auto str = to_string(num);
59 const auto len = str.length();
60
61 if ( len % 2 == 1 ) {
62 return false;
63 }
64
65 const auto half = len / 2;
66
67 for ( size_t i = 0; i != half; ++i ) {
68 if ( str[i] != str[i + half] ) {
69 return false;
70 }
71 }
72
73 return true;
74 };
75
76 cout << "Part 1: " << accumulate_invalids(ranges, is_invalid) << '\n';
77}
78
79void
80part2(const vector<tuple<long, long>>& ranges)
81{
82 auto is_invalid = [](long num) {
83 const auto str = to_string(num);
84 const auto len = str.length();
85 const auto half = len / 2;
86
87 for ( size_t i = 1; i <= half; ++i ) {
88 if ( len % i != 0 ) {
89 continue;
90 }
91
92 string pattern;
93 while ( pattern.length() != len ) {
94 pattern += str.substr(0, i);
95 }
96 if ( pattern == str ) {
97 return true;
98 }
99 }
100
101 return false;
102 };
103
104 cout << "Part 2: " << accumulate_invalids(ranges, is_invalid) << '\n';
105}
106
107} // namespace
108
109int
110main()
111{
112 auto ranges = read_file("data/day02.txt");
113 part1(ranges);
114 part2(ranges);
115}