diff --git a/src/days/09/Day09.cpp b/src/days/09/Day09.cpp index 5e1968d..2cf5166 100644 --- a/src/days/09/Day09.cpp +++ b/src/days/09/Day09.cpp @@ -1,9 +1,110 @@ #include "Day09.h" Result Day09::Task1() { - return Day::Task1(); + vector moves = parseMoves(); + set visited({{0, 0}}); + + Position head(0, 0); + Position tail(0, 0); + + Position prevHead = head; + + auto updateTail = [&head, &tail, &prevHead](){ + if (abs(head.x - tail.x) >= 2 || abs(head.y - tail.y) >= 2){ + tail = prevHead; + } + }; + + for (const Move &move : moves){ + Direction d = move.first; + int amount = move.second; + + for (int step = 0; step < amount; step++){ + prevHead = head; + head += d; + updateTail(); + visited.insert({tail.x, tail.y}); + } + } + + return to_string(visited.size()); } Result Day09::Task2() { - return Day::Task2(); -} \ No newline at end of file + vector moves = parseMoves(); + set visited({{0, 0}}); + + Position head(0, 0); + vector rope(10); + rope[0] = &head; + for (int i = 1; i < rope.size(); i++) rope[i] = new Position; + + auto updateTail = [rope](){ + for (int i = 1; i < rope.size(); i++){ + Position& current = *rope[i]; + Position& front = *rope[i - 1]; + int diffX = front.x - current.x; + int diffY = front.y - current.y; + if (abs(diffX) > 1 && abs(diffY) > 1){ + current.x += diffX / abs(diffX); + current.y += diffY / abs(diffY); + } + else if (abs(diffX) > 1){ + current.x += diffX / abs(diffX); + current.y = front.y; + } + else if (abs(diffY) > 1){ + current.y += diffY / abs(diffY); + current.x = front.x; + } + } + }; + + for (const Move &move : moves){ + Direction d = move.first; + int amount = move.second; + + for (int step = 0; step < amount; step++){ + head += d; + updateTail(); + visited.insert({rope.back()->x, rope.back()->y}); + } + } + + return to_string(visited.size()); +} + +vector Day09::parseMoves() { + vector moves; + + for (const string &line : input){ + Direction d(0, 0); + switch (line[0]) { + case 'L': + d.x = -1; + break; + case 'R': + d.x = 1; + break; + case 'U': + d.y = 1; + break; + case 'D': + d.y = -1; + break; + } + int amount = stoi(line.substr(2)); + moves.emplace_back(d, amount); + } + + return moves; +} + +Day09::Vector Day09::Vector::operator+(Vector v2) const { + return {x + v2.x, y + v2.y}; +} + +void Day09::Vector::operator+=(Vector v2) { + x += v2.x; + y += v2.y; +} diff --git a/src/days/09/Day09.h b/src/days/09/Day09.h index 0747edd..ca87a8c 100644 --- a/src/days/09/Day09.h +++ b/src/days/09/Day09.h @@ -3,8 +3,23 @@ #include "../../Day.h" class Day09 : public Day { + struct Vector { + Vector() = default; + Vector(int x, int y) : x(x), y(y) {}; + int x {}; int y {}; + Vector operator+ (Vector v2) const; + void operator+= (Vector v2); + }; + + typedef pair PositionS; + typedef Vector Position; + typedef Vector Direction; + typedef pair Move; + protected: Result Task1() override; Result Task2() override; + + vector parseMoves(); }; \ No newline at end of file