From 9cf28c64e28ad34cfb4e232c7df4909c8a09e3f1 Mon Sep 17 00:00:00 2001 From: Jan Hensel Date: Thu, 10 Dec 2020 18:01:52 +0100 Subject: [PATCH] 09: solve part 2 finally Lot easier than I thought yesterday, just walk through it with two iterators and skip the answer should you come across it. --- 09/part2/cpp/Makefile | 12 +++++++ 09/part2/cpp/main.cc | 80 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+) create mode 100644 09/part2/cpp/Makefile create mode 100644 09/part2/cpp/main.cc diff --git a/09/part2/cpp/Makefile b/09/part2/cpp/Makefile new file mode 100644 index 0000000..c577ea1 --- /dev/null +++ b/09/part2/cpp/Makefile @@ -0,0 +1,12 @@ +CXXFLAGS=-O0 --std=c++20 -Wall -Wextra + +all: solve + +solve: a.out + ./a.out < ../../input + +a.out: main.cc + g++ $(CXXFLAGS) main.cc + +clean: + rm a.out diff --git a/09/part2/cpp/main.cc b/09/part2/cpp/main.cc new file mode 100644 index 0000000..dc9f062 --- /dev/null +++ b/09/part2/cpp/main.cc @@ -0,0 +1,80 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#define NUMRANGE 25 + +using Value = long long; + +int +main(void) +{ + + std::vector xmas; + Value n; + while (std::cin >> n) { xmas.push_back(n); } + + Value answer; + auto answer_pos = xmas.begin(); + for (auto it = xmas.begin() + NUMRANGE; it < xmas.end(); it++) + { + Value n = *it; + std::set sums; + for (auto it_i = it - NUMRANGE; it_i < it; it_i++) + for (auto it_j = it - NUMRANGE; it_j < it; it_j++) + if (*it_i != *it_j) sums.insert(*it_i + *it_j); + if (!sums.contains(n)) + { + std::cerr << "answer found: " << n << std::endl; + answer = n; + answer_pos = it; + break; + } + } + + if (answer_pos == xmas.begin()) + { + std::cerr << "answer unexpectedly not found" << std::endl; + return EXIT_FAILURE; + } + + auto lb = xmas.begin(); + auto ub = xmas.begin() + 2; + while (ub != xmas.end()) + { + if (ub == answer_pos) + { + lb = answer_pos + 1; + ub = answer_pos + 1 + 2; + continue; + } + + auto sum = std::accumulate(lb, ub, 0); + + if (sum < answer) { ub++; } + else if (sum > answer) + { + lb++; + } + else + { + // contiguous sequence found + break; + } + } + + auto weakness = *std::min_element(lb, ub) + *std::max_element(lb, ub); + + std::cout << "xmas weakness: " << weakness << std::endl; + + return EXIT_SUCCESS; +} -- knotmirror 0.0.1