Refactor Graph class into a template to remove LabelGraph and WeightGraph

This commit is contained in:
2025-06-17 20:50:11 +02:00
parent 8e3ca71bda
commit b71d904770
14 changed files with 256 additions and 321 deletions

View File

@@ -32,9 +32,8 @@ void LanParty::processDataLine(const std::string& line)
void LanParty::finish()
{
const auto& vertices = lan_.getLabelVertices();
auto itTx = vertices.lower_bound(getFirstTxComputerName());
const auto itTxEnd = vertices.upper_bound(getLastTxComputerName());
auto itTx = labelMap_.lower_bound(getFirstTxComputerName());
const auto itTxEnd = labelMap_.upper_bound(getLastTxComputerName());
while (itTx != itTxEnd)
{
computeInterconnectedThreeSetCount(itTx->second);
@@ -54,15 +53,16 @@ constexpr std::string LanParty::getLastTxComputerName()
int LanParty::findOrAddVertex(const std::string& vertexId)
{
const auto& vertices = lan_.getLabelVertices();
const auto found = vertices.find(vertexId);
if (found != vertices.end())
const auto found = labelMap_.find(vertexId);
if (found != labelMap_.end())
{
return found->second;
}
else
{
return lan_.addVertex(vertexId);
int vertex = lan_.addVertex(vertexId);
labelMap_.insert({ vertexId, vertex });
return vertex;
}
}
@@ -93,6 +93,6 @@ void LanParty::computeInterconnectedThreeSetCount(const int vertexTx)
bool LanParty::canProcessVertex(const int vertexToCheck, const int vertexTx) const
{
const std::string& label{ lan_.getVertexLabel(vertexToCheck) };
return (label[0] != 't' || label > lan_.getVertexLabel(vertexTx));
const std::string& label{ lan_.getVertexData(vertexToCheck) };
return (label[0] != 't' || label > lan_.getVertexData(vertexTx));
}

View File

@@ -18,7 +18,8 @@
#include <sstream>
RamRun::RamRun(const size_t memorySize, const int maxBytes)
: memorySize_{ memorySize }, maxBytes_{ maxBytes }, nBytes_{ 0 }, vertexReferences_{ memorySize, memorySize }
: memorySize_{ memorySize }, maxBytes_{ maxBytes }, nBytes_{ 0 }, vertexReferences_{ memorySize, memorySize },
edgeWeightFunctor_{ [](int x) { return 1; } }, dijkstraResult_{}
{
vertexReferences_.fill(getUnknownVertexReference());
}
@@ -47,7 +48,7 @@ void RamRun::processDataLine(const std::string& line)
{
// Calculates initial distances.
auto graph = buildGraph();
dijkstraResult_ = graph.dijkstra(vertexReferences_[0][0]);
dijkstraResult_ = Dijkstra::run(graph, edgeWeightFunctor_, vertexReferences_[0][0]);
part1 = dijkstraResult_.distances[vertexReferences_[memorySize_ - 1][memorySize_ - 1]];
}
else if (maxBytes_ < nBytes_)
@@ -63,9 +64,9 @@ void RamRun::processDataLine(const std::string& line)
// is now blocked.
resetVertexReferences();
auto graph = buildGraph();
dijkstraResult_ = graph.dijkstra(vertexReferences_[0][0]);
if (dijkstraResult_.distances[vertexReferences_[memorySize_ - 1][memorySize_ - 1]]
== WeightGraph::getInfiniteDistance())
dijkstraResult_ = Dijkstra::run(graph, edgeWeightFunctor_, vertexReferences_[0][0]);
if (dijkstraResult_.distances[static_cast<size_t>(vertexReferences_[memorySize_ - 1][memorySize_ - 1])]
== Dijkstra::getInfiniteDistance())
{
// Path is blocked.
part2 = line;
@@ -105,9 +106,9 @@ bool RamRun::tryMarkCorrupted(const std::string& line, int& corruptedVertex)
return false;
}
WeightGraph RamRun::buildGraph()
Graph<void, void> RamRun::buildGraph()
{
WeightGraph graph;
Graph<void, void> graph;
for (size_t j = 0; j < vertexReferences_.getNRows(); j++)
{
for (size_t i = 0; i < vertexReferences_.getNColumns(); i++)
@@ -119,14 +120,14 @@ WeightGraph RamRun::buildGraph()
{
if (vertexReferences_[j][i - 1] != getNoVertexReference())
{
graph.addEdge(getVertex(graph, i - 1, j), v, 1);
graph.addEdge(getVertex(graph, i - 1, j), v);
}
}
if (j != 0)
{
if (vertexReferences_[j - 1][i] != getNoVertexReference())
{
graph.addEdge(getVertex(graph, i, j - 1), v, 1);
graph.addEdge(getVertex(graph, i, j - 1), v);
}
}
}
@@ -135,11 +136,11 @@ WeightGraph RamRun::buildGraph()
return graph;
}
int RamRun::getVertex(WeightGraph& graph, const size_t x, const size_t y)
int RamRun::getVertex(Graph<void, void>& graph, const size_t x, const size_t y)
{
if (vertexReferences_[y][x] == getUnknownVertexReference())
{
vertexReferences_[y][x] = graph.addVertex(0);
vertexReferences_[y][x] = graph.addVertex();
}
return vertexReferences_[y][x];
}

View File

@@ -13,10 +13,12 @@
// 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/ReindeerMaze.hpp>
#include <numeric>
#include <stack>
#include <aoc/ReindeerMaze.hpp>
#include <aoc/common/Dijkstra.hpp>
ReindeerMaze::ReindeerMaze(const int inputFileNameSuffix)
: LinesSolver{ inputFileNameSuffix }
@@ -40,12 +42,12 @@ void ReindeerMaze::finish()
// do not want to hardcode this.
VertexAttachedPositions vertexAttachedPositions;
WeightGraph graph{};
Graph<int, int> graph{};
auto entry = graph.addVertex(0);
auto exit = graph.addVertex(0);
buildPathSegmentGraph(graph, vertexAttachedPositions, entry, exit);
auto result = graph.dijkstra(exit);
auto result = Dijkstra::run(graph, [&graph](int edge) { return graph.getEdgeData(edge); }, exit);
part1 = result.distances[entry] / 2;
part2 = calcShortestPaths(graph, vertexAttachedPositions, entry, exit, result.distances);
}
@@ -72,7 +74,7 @@ constexpr int ReindeerMaze::getTurnCost()
// Constructs the graph of path segment incidences, starting with a graph that already contains the entry and the exit
// vertices.
void ReindeerMaze::buildPathSegmentGraph(WeightGraph& graph, VertexAttachedPositions& vertexAttachedPositions,
void ReindeerMaze::buildPathSegmentGraph(Graph<int, int>& graph, VertexAttachedPositions& vertexAttachedPositions,
const int entry, const int exit)
{
// Uses list for work items to prevent invalidation of iterators on add.
@@ -243,7 +245,7 @@ void ReindeerMaze::addCheckedIncidence(std::vector<ReindeerMazePathIncidence>& i
}
}
void ReindeerMaze::addPathSegmentEdges(WeightGraph& graph, const ReindeerMazePathIncidence& pathIncidence,
void ReindeerMaze::addPathSegmentEdges(Graph<int, int>& graph, const ReindeerMazePathIncidence& pathIncidence,
const std::vector<ReindeerMazePathIncidence>& otherPathIncidences)
{
for (auto& otherIncidence : otherPathIncidences)
@@ -267,13 +269,13 @@ std::pair<int, int> ReindeerMaze::makePositionsIdPair(const Point2& position1, c
return std::make_pair(position1.x * offset + position1.y, position2.x * offset + position2.y);
}
int ReindeerMaze::calcShortestPaths(const WeightGraph& graph,
int ReindeerMaze::calcShortestPaths(const Graph<int, int>& graph,
const VertexAttachedPositions& vertexAttachedPositions, const int entry, const int exit,
const std::vector<int>& shortestDistances)
{
std::set<int> shortestPathsVertices{};
std::stack<Graph::NeighborIterator> stack{};
std::stack<Graph<int, int>::NeighborIterator> stack{};
auto v = graph.begin(entry);
stack.emplace(v);
int cost{ 0 };
@@ -286,7 +288,7 @@ int ReindeerMaze::calcShortestPaths(const WeightGraph& graph,
auto& current = stack.top();
int newCost{ 0 };
while (current != graph.end() &&
((newCost = graph.getEdgeWeight(current->edge) + cost) + shortestDistances[current->vertex] >
((newCost = graph.getEdgeData(current->edge) + cost) + shortestDistances[current->vertex] >
shortestDistances[entry] ||
stackedVertices.contains(current->vertex)))
{
@@ -320,7 +322,7 @@ int ReindeerMaze::calcShortestPaths(const WeightGraph& graph,
if (!stack.empty())
{
stackedVertices.erase(stack.top()->vertex);
cost -= graph.getEdgeWeight(stack.top()->edge);
cost -= graph.getEdgeData(stack.top()->edge);
stack.top()++;
}
}
@@ -330,7 +332,7 @@ int ReindeerMaze::calcShortestPaths(const WeightGraph& graph,
shortestPathsVertices.erase(entry);
return std::accumulate(shortestPathsVertices.begin(), shortestPathsVertices.end(),
getNUniqueAttachedPositions(vertexAttachedPositions, shortestPathsVertices),
[&graph](int total, int x) { return total + graph.getVertexWeight(x); });
[&graph](int total, int x) { return total + graph.getVertexData(x); });
}
int ReindeerMaze::getNUniqueAttachedPositions(const VertexAttachedPositions& vertexAttachedPositions,

View File

@@ -13,41 +13,20 @@
// 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/common/WeightGraph.hpp>
#include <aoc/common/Dijkstra.hpp>
#include <limits>
#include <queue>
constexpr int WeightGraph::getInfiniteDistance()
constexpr int Dijkstra::getInfiniteDistance()
{
return std::numeric_limits<int>::max();
}
int WeightGraph::addVertex(const int weight)
Dijkstra::PathsResult Dijkstra::run(const GraphBase& graph, const std::function<int(int)>& edgeWeightFunctor,
const int source)
{
vertexWeights_.push_back(weight);
return graph_.addVertex();
}
void WeightGraph::addEdge(const int vertex1, const int vertex2, const int weight)
{
edgeWeights_.push_back(weight);
graph_.addEdge(vertex1, vertex2);
}
int WeightGraph::getVertexWeight(const int vertex) const
{
return vertexWeights_[vertex];
}
int WeightGraph::getEdgeWeight(const int edge) const
{
return edgeWeights_[edge];
}
GraphPathsResult WeightGraph::dijkstra(const int source) const
{
GraphPathsResult result(graph_.getNVertices(), getInfiniteDistance(), -1);
PathsResult result{ graph.getNVertices(), getInfiniteDistance(), -1 };
auto compare = [&result](int left, int right) { return result.distances[left] > result.distances[right]; };
std::priority_queue<int, std::vector<int>, decltype(compare)> queue{ compare };
@@ -59,9 +38,9 @@ GraphPathsResult WeightGraph::dijkstra(const int source) const
int v{ queue.top() };
queue.pop();
for (auto neighbor = begin(v); neighbor != end(); ++neighbor)
for (auto neighbor = graph.begin(v); neighbor != graph.end(); ++neighbor)
{
int newDistance{ result.distances[v] + edgeWeights_[neighbor->edge] };
int newDistance{ result.distances[v] + edgeWeightFunctor(neighbor->edge) };
if (result.distances[neighbor->vertex] > newDistance)
{
result.distances[neighbor->vertex] = newDistance;
@@ -73,13 +52,3 @@ GraphPathsResult WeightGraph::dijkstra(const int source) const
return result;
}
Graph::NeighborIterator WeightGraph::begin(const int vertex) const
{
return graph_.begin(vertex);
}
Graph::NeighborIterator WeightGraph::end() const
{
return graph_.end();
}

View File

@@ -13,36 +13,19 @@
// 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/common/Graph.hpp>
#include <aoc/common/GraphBase.hpp>
int Graph::addVertex()
size_t GraphBase::getNVertices() const
{
firstVertexIncidences_.push_back(-1);
return static_cast<int>(firstVertexIncidences_.size()) - 1;
return firstVertexIncidences.size();
}
void Graph::addEdge(const int vertex1, const int vertex2)
size_t GraphBase::getNEdges() const
{
incidenceVertices_.push_back(vertex2);
nextIncidences_.push_back(firstVertexIncidences_[vertex1]);
firstVertexIncidences_[vertex1] = static_cast<int>(incidenceVertices_.size()) - 1;
incidenceVertices_.push_back(vertex1);
nextIncidences_.push_back(firstVertexIncidences_[vertex2]);
firstVertexIncidences_[vertex2] = static_cast<int>(incidenceVertices_.size()) - 1;
return nextIncidences.size() >> 1;
}
size_t Graph::getNVertices() const
{
return firstVertexIncidences_.size();
}
size_t Graph::getNEdges() const
{
return nextIncidences_.size() >> 1;
}
bool Graph::areAdjacent(const int vertex1, const int vertex2) const
bool GraphBase::areAdjacent(const int vertex1, const int vertex2) const
{
auto it = begin(vertex1);
while (it != end())
@@ -56,12 +39,29 @@ bool Graph::areAdjacent(const int vertex1, const int vertex2) const
return false;
}
Graph::NeighborIterator Graph::begin(const int vertex) const
GraphBase::NeighborIterator GraphBase::begin(const int vertex) const
{
return { *this, vertex };
}
Graph::NeighborIterator Graph::end() const
GraphBase::NeighborIterator GraphBase::end() const
{
return { *this, -1 };
}
int GraphBase::addVertexInternal()
{
firstVertexIncidences.push_back(-1);
return static_cast<int>(firstVertexIncidences.size()) - 1;
}
void GraphBase::addEdgeInternal(const int vertex1, const int vertex2)
{
incidenceVertices.push_back(vertex2);
nextIncidences.push_back(firstVertexIncidences[vertex1]);
firstVertexIncidences[vertex1] = static_cast<int>(incidenceVertices.size()) - 1;
incidenceVertices.push_back(vertex1);
nextIncidences.push_back(firstVertexIncidences[vertex2]);
firstVertexIncidences[vertex2] = static_cast<int>(incidenceVertices.size()) - 1;
}

View File

@@ -1,53 +0,0 @@
// 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/common/LabelGraph.hpp>
int LabelGraph::addVertex(const std::string& label)
{
vertexLabels_.push_back(label);
labelVertices_.insert({ label, static_cast<int>(vertexLabels_.size()) - 1 });
return graph_.addVertex();
}
void LabelGraph::addEdge(const int vertex1, const int vertex2)
{
graph_.addEdge(vertex1, vertex2);
}
bool LabelGraph::areAdjacent(const int vertex1, const int vertex2) const
{
return graph_.areAdjacent(vertex1, vertex2);
}
const std::string& LabelGraph::getVertexLabel(const int vertex) const
{
return vertexLabels_[vertex];
}
const std::map<std::string, int>& LabelGraph::getLabelVertices() const
{
return labelVertices_;
}
Graph::NeighborIterator LabelGraph::begin(const int vertex) const
{
return graph_.begin(vertex);
}
Graph::NeighborIterator LabelGraph::end() const
{
return graph_.end();
}