Skip to content

Instantly share code, notes, and snippets.

@zntfdr
Last active January 6, 2020 09:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zntfdr/c93fc2863ac0a847a90865564ca22121 to your computer and use it in GitHub Desktop.
Save zntfdr/c93fc2863ac0a847a90865564ca22121 to your computer and use it in GitHub Desktop.
import GameplayKit
let myGraph = GKGraph()
class MyNode: GKGraphNode {
let name: String
var travelCost: [GKGraphNode: Float] = [:]
init(name: String) {
self.name = name
super.init()
}
required init?(coder aDecoder: NSCoder) {
self.name = ""
super.init()
}
override func cost(to node: GKGraphNode) -> Float {
return travelCost[node] ?? 0
}
func addConnection(to node: GKGraphNode, bidirectional: Bool = true, weight: Float) {
self.addConnections(to: [node], bidirectional: bidirectional)
travelCost[node] = weight
guard bidirectional else { return }
(node as? MyNode)?.travelCost[self] = weight
}
}
func print(_ path: [GKGraphNode]) {
path.flatMap({ $0 as? MyNode}).forEach { node in
print(node.name)
}
}
func printCost(for path: [GKGraphNode]) {
var total: Float = 0
for i in 0..<(path.count-1) {
total += path[i].cost(to: path[i+1])
}
print(total)
}
let nodeA = MyNode(name: "A")
let nodeB = MyNode(name: "B")
let nodeC = MyNode(name: "C")
let nodeD = MyNode(name: "D")
myGraph.add([nodeA, nodeB, nodeC, nodeD])
nodeA.addConnection(to: nodeB, weight: 1.1)
nodeB.addConnection(to: nodeC, weight: 0.1)
nodeC.addConnection(to: nodeD, weight: 1.3)
var path = myGraph.findPath(from: nodeA, to: nodeD)
print(path)
printCost(for: path)
let nodeS = MyNode(name: "S")
nodeS.addConnection(to: nodeA, weight: 0)
nodeS.addConnection(to: nodeD, weight: 1.5)
path = myGraph.findPath(from: nodeA, to: nodeD)
print(path)
printCost(for: path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment