Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Graph class
- -- ModuleScript with GraphNode, GraphEdge and FloydWarshall ModuleScripts inside
- -- by Ozzypig (Twitter: @Ozzypig, ozzypig.com)
- local GraphNode = require(script:WaitForChild("GraphNode"))
- local FloydWarshallMixin = require(script:WaitForChild("FloydWarshall"))
- local Graph = {}
- Graph.__index = Graph
- -- Functions relating to Floyd-Warshall algorithm implementation
- for k, v in pairs(FloydWarshallMixin) do Graph[k] = v end
- function Graph.new()
- local self = setmetatable({
- nodeCount = 0;
- nodes = {}; -- nodes[node] = node.value (usually just true)
- nodesByIndex = {};
- edgeCount = 0;
- edges = {}; -- edge[edge] = edge.value (usually weight)
- edgesByIndex = {};
- }, Graph)
- return self
- end
- function Graph:newNode(...)
- local node = GraphNode.new(...)
- node.index = self.nodeCount + 1
- self.nodes[node] = node.value
- self.nodesByIndex[node.index] = node
- self.nodeCount = self.nodeCount + 1
- return node
- end
- function Graph:newEdge(nodeOrigin, nodeTarget, ...)
- local edge = nodeOrigin:newEdgeTo(nodeTarget, ...)
- edge.index = self.edgeCount + 1
- self.edges[edge] = edge.value
- self.edgesByIndex[edge.index] = edge
- self.edgeCount = self.edgeCount + 1
- nodeOrigin:addEdge(edge)
- end
- function Graph:eachNode()
- return pairs(self.nodes)
- end
- function Graph:eachEdge()
- return pairs(self.edges)
- end
- function Graph:randomNode()
- return self.nodesByIndex[math.random(1, #self.nodesByIndex)]
- end
- function Graph:randomEdge()
- return self.edgesByIndex[math.random(1, #self.edgesByIndex)]
- end
- return Graph
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement