Skip to content

Instantly share code, notes, and snippets.

@eklitzke
Last active December 9, 2020 16:31
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 eklitzke/4fd41569a0223009c139c5998d0c4709 to your computer and use it in GitHub Desktop.
Save eklitzke/4fd41569a0223009c139c5998d0c4709 to your computer and use it in GitHub Desktop.
#include "advent/answer.h"
#include <numeric>
namespace advent2020 {
void Solution9(std::istream &input, advent::Answer &ans) {
std::vector<uint64_t> nums;
ans.ParseInts(input, nums);
// part1
constexpr size_t window_size = 25;
uint64_t target = 0;
for (auto i = nums.begin() + window_size; i != nums.end(); ++i) {
for (auto j = i - window_size; j < i - 1; ++j) {
for (auto k = j + 1; k < i; ++k) {
if (*i == *j + *k) {
goto outer;
}
}
}
target = *i;
break;
outer:;
}
ASSERT_DEBUG(target != 0);
ans.Part1(target);
// part2
for (auto i = nums.begin(), j = i + 2; j < nums.end();) {
uint64_t sum = std::accumulate(i, j, 0);
if (sum == target) {
const auto [min, max] = std::minmax_element(i, j);
ans.Part2(*min + *max);
break;
} else if (sum < target) {
++j;
} else {
++i;
ASSERT_DEBUG(std::distance(i, j) >= 2);
}
}
}
} // namespace advent2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment