From d0243fcf4d5556a17d720257ecc0097ecfd69df8 Mon Sep 17 00:00:00 2001 From: Bert Peters Date: Tue, 17 Dec 2019 07:28:39 +0100 Subject: [PATCH] Create generic bounding box function. --- 2019/src/day11.cpp | 13 +++---------- 2019/src/day13.cpp | 12 +++--------- 2019/src/point.hpp | 16 ++++++++++++++++ 3 files changed, 22 insertions(+), 19 deletions(-) diff --git a/2019/src/day11.cpp b/2019/src/day11.cpp index 2dd8302..21fb882 100644 --- a/2019/src/day11.cpp +++ b/2019/src/day11.cpp @@ -64,17 +64,10 @@ void aoc2019::day11_part2(std::istream &input, std::ostream &output) { const auto result = simulate(input, true); // Determine bounding box - using limits = std::numeric_limits; - int left_edge = limits::max(), right_edge = limits::min(), top_edge = limits::max(), bottom_edge = limits::min(); - for (auto& entry : result) { - left_edge = std::min(entry.first[0], left_edge); - right_edge = std::max(entry.first[0], right_edge); - top_edge = std::min(entry.first[1], top_edge); - bottom_edge = std::max(entry.first[1], bottom_edge); - } + auto[lower,upper] = aoc2019::bounding_box(result); - for (int y = top_edge; y <= bottom_edge; ++y) { - for (int x = left_edge; x <= right_edge; ++x) { + for (int y = lower[1]; y <= upper[1]; ++y) { + for (int x = lower[0]; x <= upper[0]; ++x) { if (auto it = result.find({x, y}); it != result.end() && it->second) { output << '#'; } else { diff --git a/2019/src/day13.cpp b/2019/src/day13.cpp index aba4aeb..f8625e6 100644 --- a/2019/src/day13.cpp +++ b/2019/src/day13.cpp @@ -41,16 +41,10 @@ namespace { // Determine bounding box using limits = std::numeric_limits; - std::int64_t left_edge = limits::max(), right_edge = limits::min(), top_edge = limits::max(), bottom_edge = limits::min(); - for (auto& entry : screen) { - left_edge = std::min(entry.first[0], left_edge); - right_edge = std::max(entry.first[0], right_edge); - top_edge = std::min(entry.first[1], top_edge); - bottom_edge = std::max(entry.first[1], bottom_edge); - } + const auto [lower, upper] = aoc2019::bounding_box(screen); - for (auto y = top_edge; y <= bottom_edge; ++y) { - for (auto x = left_edge; x <= right_edge; ++x) { + for (auto y = lower[1]; y <= upper[1]; ++y) { + for (auto x = lower[0]; x <= upper[0]; ++x) { char c = ' '; if (auto it = screen.find({x, y}); it != screen.end()) { switch (it->second) { diff --git a/2019/src/point.hpp b/2019/src/point.hpp index f82bbad..d123475 100644 --- a/2019/src/point.hpp +++ b/2019/src/point.hpp @@ -46,6 +46,22 @@ namespace aoc2019 { return result; } }; + + template + std::pair, Point> bounding_box(const std::unordered_map, Ignored> &data) { + Point lower, upper; + std::fill(lower.begin(), lower.end(), std::numeric_limits::max()); + std::fill(upper.begin(), upper.end(), std::numeric_limits::min()); + + for (auto &entry : data) { + for (int i = 0; i < N; ++i) { + lower[i] = std::min(entry.first[i], lower[i]); + upper[i] = std::max(entry.first[i], upper[i]); + } + } + + return {lower, upper}; + } } namespace std {