Repository navigation
Expand file tree
/
Copy pathday04.cpp
More file actions
65 lines (58 loc) · 1.96 KB
/
Copy pathday04.cpp
File metadata and controls
65 lines (58 loc) · 1.96 KB
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
#include <algorithm>
#include <print>
#include <ranges>
#include <string>
#include <string_view>
constexpr std::size_t cost_to_print(std::string_view barcode) {
// trim unnecessary information
while (not barcode.empty() and barcode.front() == '?') {
barcode.remove_prefix(1);
}
while (not barcode.empty() and barcode.back() == '?') {
barcode.remove_suffix(1);
}
// early exit
std::size_t const n{barcode.size()};
if (n <= 1) return 1;
// runtime "sieve-like" validation
for (std::size_t p{1}; p < n; ++p) {
bool valid{true};
for (std::size_t r{0}; r < std::min(p, n - p); ++r) {
char color{'?'};
for (std::size_t i{r}; i < n; i += p) {
char const curr{barcode[i]};
// skip over indeterminate color
if (curr == '?') continue;
if (color != '?') valid = (color == curr);
if (not valid) break;
// realized color -- assign
color = curr;
}
// important: bail out early
if (not valid) break;
}
if (valid) return p;
}
return n;
}
constexpr static auto solve = [] {
constexpr static char data_str[] {
#embed "inputs/day04.in"
};
constexpr static std::string_view input{data_str, sizeof(data_str)};
auto costs = input
| std::views::split('\n')
| std::views::filter([] (auto&& r) { return not r.empty(); })
| std::views::transform([] (auto&& r) { return std::string_view{r}; })
| std::views::transform(cost_to_print);
std::size_t const part1{std::ranges::fold_left(costs, 0zu, std::plus{})};
std::string barcode{input};
std::erase(barcode, '\n');
std::size_t const part2{cost_to_print(barcode)};
return std::pair{part1, part2};
}();
constexpr auto& [part1, part2] = solve;
int main() {
std::println("Part 1: {}", part1);
std::println("Part 2: {}", part2);
}