import tables from strformat import fmt type VertexKey = string Graph*[T] = ref object vertices: Table[VertexKey, Vertex[T]] vertexCount: int Vertex*[T] = ref object key*: VertexKey payload*: T adj: seq[Edge] Edge* = tuple toVert: VertexKey weight: int proc addVertex[T](this: Graph, vx: Vertex[T]) = this.vertices[vx.key] = vx proc addEdge(this: Graph, fromVert: VertexKey, eg: Edge) = this.vertices[fromVert].adj.add(eg) proc addEdge(this: Graph, fromVert: VertexKey, edges: varargs[Edge]) = for edge in edges: this.vertices[fromVert].adj.add(edge) proc contains(this: Graph, vx: VertexKey): bool = vx in this.vertices proc `$`(this: Graph): string = for vkey, vval in this.vertices.pairs: result &= fmt"v{vkey} -> {{" for i, edge in vval.adj: result &= fmt"v{edge.toVert} (w{edge.weight})" if i + 1 < vval.adj.len: result &= ", " result &= "} " var g = Graph[int]() g.addVertex(Vertex[int](key: "0", payload: 20)) g.addVertex(Vertex[int](key: "1", payload: 39)) g.addVertex(Vertex[int](key: "2", payload: 2983)) g.addVertex(Vertex[int](key: "3", payload: 19380)) g.addVertex(Vertex[int](key: "4", payload: 947)) g.addVertex(Vertex[int](key: "5", payload: 947)) g.addEdge("0", (toVert: "1", weight: 5), (toVert: "5", weight: 0)) g.addEdge("1", (toVert: "2", weight: 0)) g.addEdge("2", (toVert: "3", weight: 4)) g.addEdge("3", (toVert: "4", weight: 0), (toVert: "5", weight: 0)) g.addEdge("4", (toVert: "0", weight: 7)) g.addEdge("5", (toVert: "4", weight: 0)) echo g assert "2" in g