-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathday_12a.cpp
75 lines (71 loc) · 2.4 KB
/
day_12a.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <array>
#include <fstream>
#include <iostream>
#include <numeric>
#include <regex>
#include <string>
#include <vector>
std::array<int, 3> convertLineToCoordinates(std::string line) {
line.erase(std::remove_if(std::begin(line), std::end(line),
[](auto c) { return !isprint(c); }),
std::end(line));
std::array<int, 3> point;
const std::regex coord_pattern(R"(<x=(.+), y=(.+), z=(.+)>)");
std::smatch pattern_match;
std::regex_search(line, pattern_match, coord_pattern);
for (int i = 0; i < 3; i++) {
point[i] = std::stoi(pattern_match[i + 1]);
}
return point;
}
void SimulateTimeStep(std::vector<std::array<int, 3>>& positions,
std::vector<std::array<int, 3>>& velocities) {
for (int i = 0; i < positions.size(); i++) {
for (int j = i + 1; j < positions.size(); j++) {
for (int coord = 0; coord < 3; coord++) {
if (positions[i][coord] < positions[j][coord]) {
velocities[i][coord] += 1;
velocities[j][coord] -= 1;
} else if (positions[i][coord] > positions[j][coord]) {
velocities[i][coord] -= 1;
velocities[j][coord] += 1;
}
}
}
}
for (int i = 0; i < positions.size(); i++) {
for (int coord = 0; coord < 3; coord++) {
positions[i][coord] += velocities[i][coord];
}
}
}
int main(int argc, char* argv[]) {
// Get input
std::string input = "../input/day_12_input";
if (argc > 1) {
input = argv[1];
}
std::ifstream file(input);
std::string line;
std::vector<std::array<int, 3>> positions;
while (std::getline(file, line)) {
positions.push_back(convertLineToCoordinates(line));
}
std::vector<std::array<int, 3>> velocities(positions.size());
for (size_t time_step = 0; time_step < 1000; time_step++) {
SimulateTimeStep(positions, velocities);
}
int energy = 0;
for (int i = 0; i < positions.size(); i++) {
energy +=
std::accumulate(std::begin(positions[i]), std::end(positions[i]), 0,
[](const int total, const int ele) {
return std::abs(total) + std::abs(ele);
}) *
std::accumulate(std::begin(velocities[i]), std::end(velocities[i]), 0,
[](const int total, const int ele) {
return std::abs(total) + std::abs(ele);
});
}
std::cout << energy << '\n';
}