parent
0c62846bbd
commit
95361c61e0
2 changed files with 119 additions and 3 deletions
@ -1,9 +1,110 @@ |
||||
#include "Day09.h" |
||||
|
||||
Result Day09::Task1() { |
||||
return Day::Task1(); |
||||
vector<Move> moves = parseMoves(); |
||||
set<PositionS> 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(); |
||||
} |
||||
vector<Move> moves = parseMoves(); |
||||
set<PositionS> visited({{0, 0}}); |
||||
|
||||
Position head(0, 0); |
||||
vector<Position*> 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::Move> Day09::parseMoves() { |
||||
vector<Move> 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; |
||||
} |
||||
|
Loading…
Reference in new issue