From 9c515351b540e3f8ff7c73b03926ce17dd1865c0 Mon Sep 17 00:00:00 2001 From: Matthew Gretton-Dann Date: Tue, 7 Dec 2021 10:35:28 +0000 Subject: [PATCH] Add 2021 day 7 puzzles --- 2021/puzzle-07-01.cc | 44 +++++++++++++++++++++++++++++++++++++++++++ 2021/puzzle-07-02.cc | 45 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+) create mode 100644 2021/puzzle-07-01.cc create mode 100644 2021/puzzle-07-02.cc diff --git a/2021/puzzle-07-01.cc b/2021/puzzle-07-01.cc new file mode 100644 index 0000000..86a3d5a --- /dev/null +++ b/2021/puzzle-07-01.cc @@ -0,0 +1,44 @@ +// +// Created by Matthew Gretton-Dann on 07/12/2021. +// + +#include +#include +#include +#include +#include + +auto main() -> int +{ + std::vector crabs; + std::string line; + while (std::getline(std::cin, line)) { + std::size_t idx{0}; + while (idx < line.size()) { + if (line[idx] == ',') { + ++idx; + } + else { + std::size_t end{0}; + crabs.emplace_back(std::stoul(line.substr(idx), &end)); + idx += end; + } + } + } + + unsigned min_pos{0}; + unsigned min_fuel{std::numeric_limits::max()}; + auto [low_crab, high_crab] = std::minmax_element(crabs.begin(), crabs.end()); + for (auto pos{*low_crab}; pos <= *high_crab; ++pos) { + auto fuel{std::accumulate(crabs.begin(), crabs.end(), unsigned{0}, [pos](auto a, auto b) { + return a + ((b > pos) ? (b - pos) : (pos - b)); + })}; + if (fuel < min_fuel) { + min_fuel = fuel; + min_pos = pos; + } + } + + std::cout << "Minimum fuel = " << min_fuel << " at position " << min_pos << '\n'; + return 0; +} \ No newline at end of file diff --git a/2021/puzzle-07-02.cc b/2021/puzzle-07-02.cc new file mode 100644 index 0000000..7df4e93 --- /dev/null +++ b/2021/puzzle-07-02.cc @@ -0,0 +1,45 @@ +// +// Created by Matthew Gretton-Dann on 07/12/2021. +// + +#include +#include +#include +#include +#include + +auto main() -> int +{ + std::vector crabs; + std::string line; + while (std::getline(std::cin, line)) { + std::size_t idx{0}; + while (idx < line.size()) { + if (line[idx] == ',') { + ++idx; + } + else { + std::size_t end{0}; + crabs.emplace_back(std::stoul(line.substr(idx), &end)); + idx += end; + } + } + } + + unsigned min_pos{0}; + unsigned min_fuel{std::numeric_limits::max()}; + auto [low_crab, high_crab] = std::minmax_element(crabs.begin(), crabs.end()); + for (auto pos{*low_crab}; pos <= *high_crab; ++pos) { + auto fuel{std::accumulate(crabs.begin(), crabs.end(), unsigned{0}, [pos](auto a, auto b) { + unsigned dist{(b > pos) ? (b - pos) : (pos - b)}; + return a + (dist * (dist + 1)) / 2; + })}; + if (fuel < min_fuel) { + min_fuel = fuel; + min_pos = pos; + } + } + + std::cout << "Minimum fuel = " << min_fuel << " at position " << min_pos << '\n'; + return 0; +} \ No newline at end of file