Repository navigation
Expand file tree
/
Copy pathday01.cpp
More file actions
54 lines (50 loc) · 1.79 KB
/
Copy pathday01.cpp
File metadata and controls
54 lines (50 loc) · 1.79 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
#include <algorithm>
#include <charconv>
#include <flat_map>
#include <functional>
#include <print>
#include <ranges>
#include <utility>
#include <vector>
using Pair = std::pair<int, int>;
constexpr static auto solve = [] {
constexpr static char data_str[] {
#embed "inputs/day01.in"
};
// populate histogram
std::flat_map<int, int> buckets;
for (auto r : std::views::split(data_str, '\n')) {
if (r.empty()) break;
int value{0};
std::from_chars(r.begin(), r.end(), value);
++buckets[value];
}
std::vector pairs{std::from_range, buckets};
constexpr int K{3};
// partially sort the first 3
auto const front = next(begin(pairs), K);
std::ranges::nth_element(pairs, front, {}, &Pair::second);
// partially sort the last 3, skipping over the first 3
auto const back = prev(end(pairs), K);
std::ranges::nth_element(front, back, end(pairs), {}, &Pair::second);
// the histogram is now partially sorted:
//
// A1 A2 A3 XX XX XX .. XX XX B1 B2 B3
//
// A1 through A3 are global minimums; A2 may be less than A1
// B1 through B3 are global maximums; B3 may be less than B2
// All other values have unspecified order
auto const values = std::views::keys(pairs);
constexpr auto product = std::bind_back(std::ranges::fold_left, 1llu, std::multiplies{});
// part 1 is the product of the last 3
auto const part1 = product(values | std::views::reverse | std::views::take(K));
// part 2 is the product of the first 3
auto const part2 = product(values | std::views::take(K));
// return the result as a pair of answers
return std::pair{part1, part2};
}();
constexpr auto& [part1, part2] = solve;
int main() {
std::println("Part 1: {}", part1);
std::println("Part 2: {}", part2);
}