From 08fa71a5917d1715ea40535b0b61d0c6208a3f34 Mon Sep 17 00:00:00 2001 From: Eric Mertens Date: Thu, 17 Nov 2022 08:38:14 -0800 Subject: [PATCH] minor speedup through reused allocation --- 2019/16.cpp | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/2019/16.cpp b/2019/16.cpp index d515f90..ceaa856 100644 --- a/2019/16.cpp +++ b/2019/16.cpp @@ -11,17 +11,15 @@ using namespace aocpp; namespace { -auto FFT(std::size_t const start, std::vector const& prev) +auto FFT(std::size_t const start, std::vector & partial_sums, std::vector & signal) { - std::vector result; - std::vector partial_sums; - auto n = prev.size(); - result.reserve(n); + auto n = signal.size(); + + partial_sums.clear(); partial_sums.reserve(n+1); partial_sums.push_back(0); - std::int32_t acc = 0; - for (auto const x : prev) { + for (auto const x : signal) { partial_sums.push_back(acc += x); } @@ -29,12 +27,11 @@ auto FFT(std::size_t const start, std::vector const& prev) std::int32_t acc = 0; auto step = i+start+1; for (std::size_t offset = i; offset < n; offset += 4*step) { - acc += partial_sums[std::min(n, offset + 1*step)] - partial_sums[std::min(n, offset )]; - acc -= partial_sums[std::min(n, offset + 3*step)] - partial_sums[std::min(n, offset + 2*step)]; + acc += partial_sums[std::min(n, offset + 1*step)] - partial_sums[std::min(n, offset + 0*step)] + + partial_sums[std::min(n, offset + 2*step)] - partial_sums[std::min(n, offset + 3*step)]; } - result.push_back(std::abs(acc % 10)); + signal[i] = std::abs(acc % 10); } - return result; } auto Parse(std::istream & in) -> std::vector @@ -55,8 +52,9 @@ auto Compute( std::size_t offset = 0 ) -> std::string { + std::vector partial_sums; for (std::size_t i = 0; i < iterations; i++) { - signal = FFT(offset, signal); + FFT(offset, partial_sums, signal); } signal.resize(8); std::string result;