Skip to content

Instantly share code, notes, and snippets.

@HappyCerberus
Created December 1, 2022 10:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HappyCerberus/2ec5d34823f191e6ba1fc8adadc90a97 to your computer and use it in GitHub Desktop.
Save HappyCerberus/2ec5d34823f191e6ba1fc8adadc90a97 to your computer and use it in GitHub Desktop.
uint64_t max_calories(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());
});
// find the elf with the maximum number of calories
auto it = std::ranges::max_element(by_elf);
return *it; // and return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment