Add solution for "Day 21: Keypad Conundrum", part 2
This commit is contained in:
@@ -22,8 +22,11 @@ KeypadRobot::KeypadRobot(const std::map<char, Point2>&& keypad, const Point2&& f
|
||||
{
|
||||
}
|
||||
|
||||
std::string KeypadRobot::calcInputKeys(const std::string& targetOutputKeys) const
|
||||
KeypadPatternTransformation KeypadRobot::calcTransformation(const std::string& targetOutputKeys) const
|
||||
{
|
||||
KeypadPatternTransformation result{};
|
||||
result.accumulatedLengths.push_back(targetOutputKeys.size());
|
||||
|
||||
std::ostringstream stream{};
|
||||
Point2 position{ 0, 0 };
|
||||
for (const char c : targetOutputKeys)
|
||||
@@ -32,37 +35,44 @@ std::string KeypadRobot::calcInputKeys(const std::string& targetOutputKeys) cons
|
||||
|
||||
// This specific order of robot arm movements aims to reduce resulting combinations of 'A' and '<' for the
|
||||
// second robot, which expand to more key presses starting with the third robot.
|
||||
bool horizontalFirst{ (next.x < position.x && !(next.x == forbidden_.x && position.y == forbidden_.y)) ||
|
||||
(position.x == forbidden_.x && next.y == forbidden_.y) };
|
||||
bool horizontalFirst{ (next.x < position.x && !isForbidden(next.x, position.y)) ||
|
||||
isForbidden(position.x, next.y) };
|
||||
if (horizontalFirst)
|
||||
{
|
||||
move(stream, next.x - position.x, '>', '<');
|
||||
move(stream, next.x - position.x, '>', '<', result.nDuplicates);
|
||||
}
|
||||
move(stream, next.y - position.y, 'v', '^');
|
||||
move(stream, next.y - position.y, 'v', '^', result.nDuplicates);
|
||||
if (!horizontalFirst)
|
||||
{
|
||||
move(stream, next.x - position.x, '>', '<');
|
||||
move(stream, next.x - position.x, '>', '<', result.nDuplicates);
|
||||
}
|
||||
stream << 'A';
|
||||
|
||||
result.parts.push_back(stream.str());
|
||||
stream.str("");
|
||||
|
||||
position = next;
|
||||
}
|
||||
return stream.str();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void KeypadRobot::move(std::ostringstream& stream, const int delta, const char positive, const char negative) const
|
||||
void KeypadRobot::move(std::ostringstream& stream, const int delta, const char positive, const char negative,
|
||||
int& nDuplicates) const
|
||||
{
|
||||
if (delta > 0)
|
||||
{
|
||||
for (int i{ 0 }; i < delta; i++)
|
||||
{
|
||||
stream << positive;
|
||||
}
|
||||
stream << positive;
|
||||
nDuplicates += delta - 1;
|
||||
}
|
||||
else
|
||||
else if (delta < 0)
|
||||
{
|
||||
for (int i{ 0 }; i < -delta; i++)
|
||||
{
|
||||
stream << negative;
|
||||
}
|
||||
stream << negative;
|
||||
nDuplicates -= delta + 1;
|
||||
}
|
||||
}
|
||||
|
||||
bool KeypadRobot::isForbidden(const int x, const int y) const
|
||||
{
|
||||
return x == forbidden_.x && y == forbidden_.y;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user