aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorClyne Sullivan <clyne@bitgloo.com>2022-12-09 03:35:07 -0500
committerClyne Sullivan <clyne@bitgloo.com>2022-12-09 03:35:07 -0500
commit58a63ee504f58e8ad42b2ae9f2d3bdddeec73957 (patch)
tree3491e4a5e1514bccd3c3f08cc4155f60593cf2bf
parent38ab065eaaf98f189c13aeaecdd5c1ba6c940c74 (diff)
add day 9 (c++)
-rw-r--r--day9/part1.cpp55
-rw-r--r--day9/part2.cpp59
2 files changed, 114 insertions, 0 deletions
diff --git a/day9/part1.cpp b/day9/part1.cpp
new file mode 100644
index 0000000..ecfbdd6
--- /dev/null
+++ b/day9/part1.cpp
@@ -0,0 +1,55 @@
+#include <algorithm>
+#include <iostream>
+#include <list>
+#include <string>
+#include <tuple>
+#include <vector>
+
+int main()
+{
+ std::vector<std::pair<char, int>> steps;
+
+ while (1) {
+ std::string line;
+ std::getline(std::cin, line);
+ if (std::cin.eof())
+ break;
+
+ steps.emplace_back(line.front(), stoi(line.substr(2)));
+ }
+
+ int hx = 0, hy = 0, tx = 0, ty = 0;
+ std::list<std::pair<int, int>> locs;
+ locs.emplace_back(0, 0);
+
+ for (const auto& [dir, count] : steps) {
+ for (int i = 0; i < count; ++i) {
+ //std::cout << hx << ", " << hy << " " << tx << ", " << ty << std::endl;
+
+ if (dir == 'U')
+ ++hy;
+ else if (dir == 'D')
+ --hy;
+ else if (dir == 'R')
+ ++hx;
+ else if (dir == 'L')
+ --hx;
+
+ if (std::abs(hx - tx) > 1 || std::abs(hy - ty) > 1) {
+ if (hx != tx)
+ tx += hx > tx ? 1 : -1;
+ if (hy != ty)
+ ty += hy > ty ? 1 : -1;
+
+ if (std::find(locs.cbegin(), locs.cend(), std::pair{tx, ty}) == locs.cend()) {
+ locs.emplace_back(tx, ty);
+ }
+ }
+ }
+ }
+
+ std::cout << locs.size() << std::endl;
+
+ return 0;
+}
+
diff --git a/day9/part2.cpp b/day9/part2.cpp
new file mode 100644
index 0000000..d6da81b
--- /dev/null
+++ b/day9/part2.cpp
@@ -0,0 +1,59 @@
+#include <algorithm>
+#include <iostream>
+#include <list>
+#include <string>
+#include <tuple>
+#include <vector>
+
+int main()
+{
+ std::vector<std::pair<char, int>> steps;
+
+ while (1) {
+ std::string line;
+ std::getline(std::cin, line);
+ if (std::cin.eof())
+ break;
+
+ steps.emplace_back(line.front(), stoi(line.substr(2)));
+ }
+
+ std::vector<std::pair<int, int>> knots (10, {0, 0});
+ std::list<std::pair<int, int>> locs;
+ locs.emplace_back(0, 0);
+
+ for (const auto& [dir, count] : steps) {
+ for (int i = 0; i < count; ++i) {
+ auto& [x0, y0] = knots[0];
+
+ if (dir == 'U')
+ ++y0;
+ else if (dir == 'D')
+ --y0;
+ else if (dir == 'R')
+ ++x0;
+ else if (dir == 'L')
+ --x0;
+
+ for (int j = 1; j < knots.size(); ++j) {
+ auto& [hx, hy] = knots[j - 1];
+ auto& [tx, ty] = knots[j];
+
+ if (std::abs(hx - tx) > 1 || std::abs(hy - ty) > 1) {
+ if (hx != tx)
+ tx += hx > tx ? 1 : -1;
+ if (hy != ty)
+ ty += hy > ty ? 1 : -1;
+ }
+
+ if (std::find(locs.cbegin(), locs.cend(), knots.back()) == locs.cend())
+ locs.emplace_back(knots.back());
+ }
+ }
+ }
+
+ std::cout << locs.size() << std::endl;
+
+ return 0;
+}
+