Advertisement
Guest User

Untitled

a guest
Dec 12th, 2019
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. #include <array>
  2. #include <fstream>
  3. #include <numeric>
  4. #include <regex>
  5. #include <vector>
  6.  
  7. namespace {
  8.   using namespace std;
  9.  
  10.   auto parse(ifstream input) {
  11.     array<vector<pair<int, int>>, 3> axes;
  12.     regex line_regex("<x=(-?\\d+), y=(-?\\d+), z=(-?\\d+)>");
  13.     string line;
  14.     while (getline(input, line)) {
  15.       smatch match;
  16.       regex_match(line, match, line_regex);
  17.       axes[0].push_back({ stoi(match[1]), 0 });
  18.       axes[1].push_back({ stoi(match[2]), 0 });
  19.       axes[2].push_back({ stoi(match[3]), 0 });
  20.     }
  21.     return axes;
  22.   }
  23.  
  24.   void step(vector<pair<int, int>>& moons) {
  25.     for (auto& [p1, v1] : moons) {
  26.       for (auto&& [p2, v2] : moons) {
  27.         if (p2 > p1)
  28.           v1++;
  29.         if (p2 < p1)
  30.           v1--;
  31.       }
  32.     }
  33.     for (auto& [p, v] : moons)
  34.       p += v;
  35.   }
  36.  
  37.   auto part1(ifstream input) {
  38.     auto axes = parse(move(input));
  39.     for (int i = 0; i < 1000; i++)
  40.       for (auto& axis : axes)
  41.         step(axis);
  42.     int energy = 0;
  43.     for (int i = 0; i < axes[0].size(); i++) {
  44.       int potential = 0;
  45.       int kinetic = 0;
  46.       for (auto&& axis : axes) {
  47.         auto&& [p, v] = axis[i];
  48.         potential += abs(p);
  49.         kinetic += abs(v);
  50.       }
  51.       energy += potential * kinetic;
  52.     }
  53.     return energy;
  54.   }
  55.  
  56.   auto part2(ifstream input) {
  57.     auto axes = parse(move(input));
  58.     long long total = 1;
  59.     for (auto&& first : axes) {
  60.       auto axis = first;
  61.       int steps = 0;
  62.       do {
  63.         step(axis);
  64.         steps++;
  65.       } while (axis != first);
  66.       total = lcm(total, steps);
  67.     }
  68.     return total;
  69.   }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement