Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "2022_utils.h"
- using namespace std;
- namespace {
- template <typename T> int sgn(T val) {
- return (T(0) < val) - (val < T(0));
- }
- auto part1() {
- auto s = load_strings("2022/2022_day09_input.txt");
- int64_t result = 0;
- using P = pair<int, int>;
- set<P> all_tail_pos;
- P head_pos{ 0, 0, };
- P tail_pos{ 0, 0, };
- all_tail_pos.insert(tail_pos);
- for (auto& ss : s) {
- char dir;
- int steps;
- sscanf_s(ss.c_str(), "%c %d", &dir, 1, &steps);
- for (int i = 0; i < steps; ++i) {
- switch (dir) {
- case 'R': {
- head_pos.first += 1;
- }break;
- case 'L': {
- head_pos.first -= 1;
- } break;
- case 'U': {
- head_pos.second -= 1;
- } break;
- case 'D': {
- head_pos.second += 1;
- } break;
- };
- int tail_to_head_x = head_pos.first - tail_pos.first;
- int tail_to_head_y = head_pos.second - tail_pos.second;
- if (abs(tail_to_head_x) >= 2 || abs(tail_to_head_y) >= 2) {
- tail_pos.first += sgn(tail_to_head_x);
- tail_pos.second += sgn(tail_to_head_y);
- }
- all_tail_pos.insert(tail_pos);
- }
- }
- return all_tail_pos.size();
- }
- auto part2() {
- auto s = load_strings("2022/2022_day09_input.txt");
- int64_t result = 0;
- using P = pair<int, int>;
- set<P> all_tail_pos;
- vector<P> rope(10, P{0, 0});
- all_tail_pos.insert(rope.back());
- for (auto& ss : s) {
- char dir;
- int steps;
- sscanf_s(ss.c_str(), "%c %d", &dir, 1, &steps);
- for (int i = 0; i < steps; ++i) {
- switch (dir) {
- case 'R': {
- rope[0].first += 1;
- } break;
- case 'L': {
- rope[0].first -= 1;
- } break;
- case 'U': {
- rope[0].second -= 1;
- } break;
- case 'D': {
- rope[0].second += 1;
- } break;
- };
- for (int i = 0; i < rope.size() - 1; ++i) {
- int tail_to_head_x = rope[i].first - rope[i + 1].first;
- int tail_to_head_y = rope[i].second - rope[i + 1].second;
- if (abs(tail_to_head_x) >= 2 || abs(tail_to_head_y) >= 2) {
- rope[i + 1].first += sgn(tail_to_head_x);
- rope[i + 1].second += sgn(tail_to_head_y);
- }
- }
- all_tail_pos.insert(rope.back());
- }
- }
- return all_tail_pos.size();
- }
- }
- namespace y2022 {
- void day09() {
- cout << "part 1: " << part1() << "\n";
- cout << "part 2: " << part2() << "\n";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement