Add solution for "Day 21: Keypad Conundrum", part 1
This commit is contained in:
68
src/extra/KeypadRobot.cpp
Normal file
68
src/extra/KeypadRobot.cpp
Normal file
@@ -0,0 +1,68 @@
|
||||
// Solutions to the Advent Of Code 2024.
|
||||
// Copyright (C) 2025 Stefan Müller
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify it under
|
||||
// the terms of the GNU General Public License as published by the Free Software
|
||||
// Foundation, either version 3 of the License, or (at your option) any later
|
||||
// version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
#include <aoc/extra/KeypadRobot.hpp>
|
||||
|
||||
#include <sstream>
|
||||
|
||||
KeypadRobot::KeypadRobot(const std::map<char, Point2>&& keypad, const Point2&& forbidden)
|
||||
: keypad_{ keypad }, forbidden_{ forbidden }
|
||||
{
|
||||
}
|
||||
|
||||
std::string KeypadRobot::calcInputKeys(const std::string& targetOutputKeys) const
|
||||
{
|
||||
std::ostringstream stream{};
|
||||
Point2 position{ 0, 0 };
|
||||
for (const char c : targetOutputKeys)
|
||||
{
|
||||
Point2 next = keypad_.at(c);
|
||||
|
||||
// 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) };
|
||||
if (horizontalFirst)
|
||||
{
|
||||
move(stream, next.x - position.x, '>', '<');
|
||||
}
|
||||
move(stream, next.y - position.y, 'v', '^');
|
||||
if (!horizontalFirst)
|
||||
{
|
||||
move(stream, next.x - position.x, '>', '<');
|
||||
}
|
||||
stream << 'A';
|
||||
position = next;
|
||||
}
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
void KeypadRobot::move(std::ostringstream& stream, const int delta, const char positive, const char negative) const
|
||||
{
|
||||
if (delta > 0)
|
||||
{
|
||||
for (int i{ 0 }; i < delta; i++)
|
||||
{
|
||||
stream << positive;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int i{ 0 }; i < -delta; i++)
|
||||
{
|
||||
stream << negative;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user