Skip to content

Instantly share code, notes, and snippets.

@HappyCerberus
Last active December 1, 2022 10:38
Show Gist options
  • Save HappyCerberus/4cb796ee4730762ea9abf374ea1760a4 to your computer and use it in GitHub Desktop.
Save HappyCerberus/4cb796ee4730762ea9abf374ea1760a4 to your computer and use it in GitHub Desktop.
uint64_t top_three(const std::vector<std::string>& data) {
auto by_elf = data |
// group by elf: range{range{string}}
std::views::lazy_split(std::string{}) |
// sum up the calories for each elf: range{uint64_t}
std::views::transform([](const auto& elf) -> uint64_t {
// std::string -> uint64_t
auto to_unsigned =
[](const auto& in) { return std::stoull(in); };
// make a view of uint64_t: range{string} -> range{uint64_t}
auto rng = elf |
std::views::transform(to_unsigned) |
std::views::common; // std::reduce requires a common range
// reduce into the sum: range{uint64_t} -> uint64_t
return std::reduce(rng.begin(), rng.end());
});
std::vector<uint64_t> top(3);
// We cannot sort a view, but can partial sort into a vector of three elements
std::ranges::partial_sort_copy(by_elf, top, std::greater<>{});
// Sum up the top three
return std::reduce(top.begin(), top.end());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment