Skip to content

Instantly share code, notes, and snippets.

@glubo
Last active December 6, 2022 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glubo/a68d60832cabb76ce3bf2f109e33f4c8 to your computer and use it in GitHub Desktop.
Save glubo/a68d60832cabb76ce3bf2f109e33f4c8 to your computer and use it in GitHub Desktop.
data class Vertex(
val id: String,
)
data class Edge(
val vertexA: Vertex,
val vertexB: Vertex
) {
val vertices: List<Vertex> = listOf(vertexA, vertexB)
override fun toString(): String {
return "Edge(${vertices[0].id} <=> ${vertices[1].id})"
}
}
data class Graph(
val vertices: List<Vertex>,
val edges: List<Edge>,
)
fun simplifyGraph(inputGraph: Graph): Graph {
val visitedVertices = mutableListOf<Vertex>()
val usedEdges = mutableListOf<Edge>()
val edgeMap = inputGraph.edges.flatMap { edge ->
edge.vertices.map { Pair(it, edge) }
}.groupBy(
{ it.first },
{ it.second }
)
val stack: ArrayDeque<Pair<Edge?, Vertex>> = ArrayDeque(
listOf(
Pair(null, inputGraph.vertices.first())
)
)
while (!stack.isEmpty()) {
val currentPair = stack.removeLast()
val currentVertex = currentPair.second
if (!visitedVertices.contains(currentVertex)) {
visitedVertices.add(currentVertex)
currentPair.first?.let { usedEdges.add(it) }
edgeMap[currentVertex]?.forEach { currentEdge ->
val unvisitedVertex = currentEdge.vertices.filter { !visitedVertices.contains(it) }
.firstOrNull()
unvisitedVertex?.let {
stack.add(Pair(currentEdge, it))
}
}
}
}
return Graph(
visitedVertices,
usedEdges
)
}
fun main(args: Array<String>) {
val vertA = Vertex("A")
val vertB = Vertex("B")
val vertC = Vertex("C")
val vertD = Vertex("D")
val vertE = Vertex("E")
val graph = Graph(
listOf(vertA, vertB, vertC, vertD, vertE),
listOf(
Edge(vertA, vertB),
Edge(vertB, vertC),
Edge(vertC, vertD),
Edge(vertD, vertA),
Edge(vertA, vertE),
Edge(vertB, vertE),
Edge(vertC, vertE),
Edge(vertD, vertE),
)
)
println(
"Original graph: $graph"
)
println(
"Simplified graph: ${simplifyGraph(graph)}"
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment