Last active
November 2, 2021 14:20
-
-
Save donn/84f639b1f9eab009832b9dbc8454dfff to your computer and use it in GitHub Desktop.
Swift Uniform Cost Search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env quips | |
/* | |
Requires quips - github.com/donn/quips | |
yeet | |
Swift | |
-- | |
This is free and unencumbered software released into the public domain. | |
Anyone is free to copy, modify, publish, use, compile, sell, or | |
distribute this software, either in source code form or as a compiled | |
binary, for any purpose, commercial or non-commercial, and by any | |
means. | |
In jurisdictions that recognize copyright laws, the author or authors | |
of this software dedicate any and all copyright interest in the | |
software to the public domain. We make this dedication for the benefit | |
of the public at large and to the detriment of our heirs and | |
successors. We intend this dedication to be an overt act of | |
relinquishment in perpetuity of all present and future rights to this | |
software under copyright law. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | |
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. | |
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR | |
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, | |
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR | |
OTHER DEALINGS IN THE SOFTWARE. | |
For more information, please refer to <http://unlicense.org/> | |
*/ | |
@quipgh SwiftPriorityQueue:davecom/SwiftPriorityQueue:1.3.0 | |
struct Edge { | |
let from: String | |
let to: String | |
let cost: Int | |
} | |
struct Node: Comparable { | |
let name: String | |
let cost: Int | |
let path: [String] | |
static func <(lhs: Node, rhs: Node) -> Bool { | |
return lhs.cost < rhs.cost | |
} | |
static func ==(lhs: Node, rhs: Node) -> Bool { | |
return lhs.cost == rhs.cost | |
} | |
} | |
struct Graph { | |
let edgesByNode: [String: [Edge]] | |
init(_ edges: [Edge]) { | |
var edgesByNode: [String: [Edge]] = [:] | |
for edge in edges { | |
edgesByNode[edge.from] = edgesByNode[edge.from] ?? [] | |
edgesByNode[edge.from]!.append(edge) | |
} | |
self.edgesByNode = edgesByNode | |
} | |
func uniformCostSearch(from start: String, to goal: String) -> (path: [String], cost: Int)? { | |
var frontier: PriorityQueue<Node> = PriorityQueue(ascending: true) | |
var explored: Set<String> = [] | |
frontier.push(Node(name: start, cost: 0, path: [])) | |
while true { | |
guard let current = frontier.pop() else { | |
return nil | |
} | |
print("Arrived at \(current.name)") | |
explored.insert(current.name) | |
let currentPath = current.path + [current.name] | |
let currentCost = current.cost | |
if current.name == goal { | |
print("\(current.name) is the goal. Leaving...") | |
return (path: currentPath, cost: currentCost) | |
} else { | |
print("\(current.name) is not the goal. Continuing...") | |
} | |
let edges = edgesByNode[current.name] ?? [] | |
for edge in edges { | |
let totalCost = currentCost + edge.cost | |
print("Found an edge from \(edge.from) to \(edge.to) with cost \(edge.cost) (Total: \(currentCost) + \(edge.cost) = \(totalCost)).") | |
if explored.contains(edge.to) { | |
print("Node \(edge.to) already explored. Continuing...") | |
continue | |
} | |
var foundStop: Node? = nil | |
for stop in frontier { | |
if stop.name == edge.to { | |
foundStop = stop | |
} | |
} | |
if let stop = foundStop { | |
if totalCost < stop.cost { | |
print("Found a cheaper way to \(edge.to) (\(totalCost) vs \(stop.cost)). The more expensive one will be replaced.") | |
frontier.remove(stop) | |
} else { | |
print("There is already a better way to \(edge.to) costing \(stop.cost) on the frontier.") | |
continue | |
} | |
} else { | |
print("The node \(edge.to) was not explored or in the frontier, so it will be added.") | |
} | |
frontier.push(Node(name: edge.to, cost: totalCost, path: currentPath)) | |
} | |
} | |
} | |
} | |
let simple = false | |
if simple { | |
let graph = Graph([ | |
Edge(from: "S", to: "B", cost: 5), | |
Edge(from: "S", to: "D", cost: 3), | |
Edge(from: "B", to: "C", cost: 1), | |
Edge(from: "C", to: "E", cost: 6), | |
Edge(from: "C", to: "G", cost: 8), | |
Edge(from: "D", to: "E", cost: 2), | |
Edge(from: "D", to: "F", cost: 2), | |
Edge(from: "E", to: "B", cost: 4), | |
Edge(from: "F", to: "G", cost: 3), | |
Edge(from: "G", to: "E", cost: 4), | |
]) // Expected solution: SDFG, 8 | |
print(graph.uniformCostSearch(from: "S", to: "G") ?? "No solution.") | |
} else { | |
let graph = Graph([ | |
Edge(from: "S", to: "d", cost: 3), | |
Edge(from: "S", to: "e", cost: 9), | |
Edge(from: "S", to: "p", cost: 1), | |
Edge(from: "b", to: "a", cost: 2), | |
Edge(from: "c", to: "a", cost: 2), | |
Edge(from: "d", to: "b", cost: 1), | |
Edge(from: "d", to: "c", cost: 8), | |
Edge(from: "d", to: "e", cost: 2), | |
Edge(from: "e", to: "h", cost: 1), | |
Edge(from: "e", to: "r", cost: 9), | |
Edge(from: "h", to: "q", cost: 4), | |
Edge(from: "h", to: "p", cost: 4), | |
Edge(from: "f", to: "G", cost: 5), | |
Edge(from: "p", to: "q", cost: 15), | |
Edge(from: "q", to: "r", cost: 3), | |
Edge(from: "r", to: "f", cost: 5) | |
]) // Expected Solution: SdehqrfG, 23 | |
print(graph.uniformCostSearch(from: "S", to: "G") ?? "No solution.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment