Add solution for "Day 20: Race Condition", part 1

This commit is contained in:
2025-06-03 19:29:34 +02:00
parent 32a239d14a
commit 43f1798343
4 changed files with 144 additions and 0 deletions

View File

@@ -40,6 +40,7 @@
#include <aoc/ChronospatialComputer.hpp>
#include <aoc/RamRun.hpp>
#include <aoc/LinenLayout.hpp>
#include <aoc/RaceCondition.hpp>
#include <aoc/LanParty.hpp>
void Program::run()
@@ -77,6 +78,7 @@ void Program::runSolvers()
runSolver<ChronospatialComputer>(solverEngine);
runSolver<RamRun>(solverEngine);
runSolver<LinenLayout>(solverEngine);
runSolver<RaceCondition>(solverEngine);
runSolver<LanParty>(solverEngine);
}

91
src/RaceCondition.cpp Normal file
View File

@@ -0,0 +1,91 @@
// 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/RaceCondition.hpp>
RaceCondition::RaceCondition(const int threshold)
: threshold_{ threshold }
{
}
const std::string RaceCondition::getPuzzleName() const
{
return "Race Condition";
}
const int RaceCondition::getPuzzleDay() const
{
return 20;
}
void RaceCondition::finish()
{
int time{ 0 };
Grid<int> times{ lines.size(), lines[0].size() };
// Fills the grid with a number that is guaranteed to be greater than the length of the path.
times.fill(static_cast<int>(times.getNColumns() * times.getNRows()));
Point2 position{ findChar(getStartChar()) };
Point2 previous{ -1, -1 };
while (position != previous)
{
// Tracks time for current position.
times.cell(position) = time++;
// Checks if there is a cheat leading to the current position.
checkCheat(position, times);
// Progresses the race path.
auto oldPosition = position;
for (const auto& direction : Point2::cardinalDirections)
{
auto next = position + direction;
if (next != previous && getCharAt(next) != getWallChar())
{
position = next;
break;
}
}
previous = oldPosition;
}
}
constexpr char RaceCondition::getStartChar()
{
return 'S';
}
constexpr char RaceCondition::getWallChar()
{
return '#';
}
constexpr int RaceCondition::getCheatLength()
{
return 2;
}
void RaceCondition::checkCheat(const Point2& position, Grid<int>& times)
{
auto time = times.cell(position);
for (auto& direction : doubleSteps_)
{
auto other = position + direction;
if (isInBounds(other) && time >= threshold_ + times.cell(other) + getCheatLength())
{
part1++;
}
}
}