From 3d60859079862cd59472fc1fd47195c5722b8990 Mon Sep 17 00:00:00 2001 From: Bert Peters Date: Thu, 12 Dec 2019 08:15:01 +0100 Subject: [PATCH] Implement day 12 part 1. --- 2019/inputs/12.txt | 4 +++ 2019/src/day12.cpp | 67 +++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 2019/inputs/12.txt diff --git a/2019/inputs/12.txt b/2019/inputs/12.txt new file mode 100644 index 0000000..317dac1 --- /dev/null +++ b/2019/inputs/12.txt @@ -0,0 +1,4 @@ + + + + diff --git a/2019/src/day12.cpp b/2019/src/day12.cpp index 16cb2a8..9ab3a1a 100644 --- a/2019/src/day12.cpp +++ b/2019/src/day12.cpp @@ -1,8 +1,73 @@ #include +#include +#include #include "days.hpp" +#include "point.hpp" + +namespace { + typedef aoc2019::Point point_t; + using aoc2019::from_chars; + + std::vector read_moons(std::istream &input) { + std::vector moons; + + std::regex regex(R"(^$)"); + std::smatch results; + + for (std::string buffer; std::getline(input, buffer);) { + if (!std::regex_match(buffer, results, regex)) { + throw std::domain_error(buffer); + } + + point_t moon; + for (int i = 0; i < 3; ++i) from_chars(results[i + 1].str(), moon[i]); + + moons.emplace_back(moon); + } + + return moons; + } + + void update_velocity(const point_t &a, point_t &va, const point_t &b, point_t &vb) { + for (int i = 0; i < a.size(); ++i) { + if (a[i] < b[i]) { + va[i]++; + vb[i]--; + } else if (a[i] > b[i]) { + va[i]--; + vb[i]++; + } + } + } + + void update_velocities(const std::vector &positions, std::vector &velocities) { + for (int i = 0; i < positions.size(); ++i) { + for (int j = i + 1; j < positions.size(); ++j) { + update_velocity(positions[i], velocities[i], positions[j], velocities[j]); + } + } + } +} void aoc2019::day12_part1(std::istream &input, std::ostream &output) { - output << "Not implemented\n"; + auto moons = read_moons(input); + std::vector velocities(moons.size()); + + for (int i = 0; i < 1000; ++i) { + update_velocities(moons, velocities); + + for (int j = 0; j < moons.size(); ++j) { + moons[j] += velocities[j]; + } + } + + int energy = 0; + + for (int i = 0; i < moons.size(); ++i) { + energy += moons[i].l1() * velocities[i].l1(); + } + + output << energy << std::endl; } void aoc2019::day12_part2(std::istream &input, std::ostream &output) {