Skip to content

Commit

Permalink
Adding transpose function and corresponding tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
toadkarter committed Oct 3, 2023
1 parent 23370f6 commit b19bbf1
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
5 changes: 5 additions & 0 deletions include/graaflib/graph.h
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,11 @@ using directed_graph = graph<VERTEX_T, EDGE_T, graph_type::DIRECTED>;
template <typename VERTEX_T, typename EDGE_T>
using undirected_graph = graph<VERTEX_T, EDGE_T, graph_type::UNDIRECTED>;

template <typename VERTEX_T, typename EDGE_T>
void get_transposed_graph(
const directed_graph<VERTEX_T, EDGE_T>& graph,
directed_graph<VERTEX_T, EDGE_T>& out_transposed_graph);

} // namespace graaf

#include "graph.tpp"
25 changes: 25 additions & 0 deletions include/graaflib/graph.tpp
Original file line number Diff line number Diff line change
Expand Up @@ -213,4 +213,29 @@ void graph<VERTEX_T, EDGE_T, GRAPH_TYPE_V>::remove_edge(
std::abort();
}

template <typename VERTEX_T, typename EDGE_T>
void get_transposed_graph(
const directed_graph<VERTEX_T, EDGE_T>& graph,
directed_graph<VERTEX_T, EDGE_T>& out_transposed_graph) {
for (const auto [edge_vertices, edge] : graph.get_edges()) {
const auto [vertex_id_lhs, vertex_id_rhs] = edge_vertices;

auto vertex_value_lhs = graph.get_vertex(vertex_id_lhs);
auto vertex_value_rhs = graph.get_vertex(vertex_id_rhs);
auto edge_type = edge;

if (!out_transposed_graph.has_vertex(vertex_id_lhs)) {
auto vertex_id =
out_transposed_graph.add_vertex(vertex_value_lhs, vertex_id_lhs);
}

if (!out_transposed_graph.has_vertex(vertex_id_rhs)) {
auto vertex_id =
out_transposed_graph.add_vertex(vertex_value_rhs, vertex_id_rhs);
}

out_transposed_graph.add_edge(vertex_id_rhs, vertex_id_lhs, edge_type);
}
}

} // namespace graaf
24 changes: 24 additions & 0 deletions test/graaflib/graph_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -247,4 +247,28 @@ TYPED_TEST(GraphTest, ConstGetter) {
ASSERT_NO_THROW(test_getters_on_const_graph(graph));
}

TEST(GraphTest, Transpose) {
// GIVEN
using graph_t = directed_graph<int, int>;
graph_t graph{};
const auto vertex_id_1 = graph.add_vertex(1);
const auto vertex_id_2 = graph.add_vertex(2);
const auto vertex_id_3 = graph.add_vertex(3);
graph.add_edge(vertex_id_1, vertex_id_2, 100);
graph.add_edge(vertex_id_2, vertex_id_3, 200);
graph.add_edge(vertex_id_3, vertex_id_1, 300);

// WHEN
graph_t transposed_graph{};
get_transposed_graph(graph, transposed_graph);

// THEN
EXPECT_EQ(get_weight(transposed_graph.get_edge(vertex_id_2, vertex_id_1)),
100);
EXPECT_EQ(get_weight(transposed_graph.get_edge(vertex_id_3, vertex_id_2)),
200);
EXPECT_EQ(get_weight(transposed_graph.get_edge(vertex_id_1, vertex_id_3)),
300);
}

} // namespace graaf

0 comments on commit b19bbf1

Please sign in to comment.