From f42d50a4790ba88c6eba9a687e43001ab6d8a7cd Mon Sep 17 00:00:00 2001 From: Jack Bond-Preston Date: Sun, 12 Dec 2021 03:08:17 +0000 Subject: [PATCH] day 7 Signed-off-by: Jack Bond-Preston --- 7/7a.cpp | 38 ++++++++++++++++++++++++++++++++++++++ 7/7b.cpp | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 7/7a.cpp create mode 100644 7/7b.cpp diff --git a/7/7a.cpp b/7/7a.cpp new file mode 100644 index 0000000..c38e049 --- /dev/null +++ b/7/7a.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +#include +#include + +int main() { + std::ifstream infile("input.txt"); + + std::vector positions {}; + + int curr = 0; + char comma; + while (infile >> curr) { + positions.push_back(curr); + infile >> comma; + } + + int lowest = *std::min_element(std::begin(positions), std::end(positions)); + int highest = *std::max_element(std::begin(positions), std::end(positions)); + + int lowest_cost = INT_MAX; + int best_position = 0; + + for (int i = lowest; i < highest; i++) { + int fuel_cost = 0; + for (const auto &p : positions) { + fuel_cost += std::abs(p - i); + } + + if (fuel_cost < lowest_cost) { + lowest_cost = fuel_cost; + best_position = i; + } + } + + std::cout << lowest_cost << std::endl; +} \ No newline at end of file diff --git a/7/7b.cpp b/7/7b.cpp new file mode 100644 index 0000000..10fdabe --- /dev/null +++ b/7/7b.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +#include +#include + +int main() { + std::ifstream infile("input.txt"); + + std::vector positions {}; + + int curr = 0; + char comma; + while (infile >> curr) { + positions.push_back(curr); + infile >> comma; + } + + int lowest = *std::min_element(std::begin(positions), std::end(positions)); + int highest = *std::max_element(std::begin(positions), std::end(positions)); + + int lowest_cost = INT_MAX; + int best_position = 0; + + for (int i = lowest; i < highest; i++) { + int fuel_cost = 0; + for (const auto &p : positions) { + int next_cost = 1; + for (int j = 0; j < std::abs(p - i); j++, next_cost++) { + fuel_cost += next_cost; + } + } + + if (fuel_cost < lowest_cost) { + lowest_cost = fuel_cost; + best_position = i; + } + } + + std::cout << lowest_cost << std::endl; +} \ No newline at end of file