@@ -120,18 +120,18 @@ func tspPaths<T>(_ permutations: [[T]]) -> [[T]] {
120
120
print ( tspPaths ( testPerms) )
121
121
122
122
func solveTSP< T> ( cities: [ T ] , distances: [ T : [ T : Int ] ] ) -> ( solution: [ T ] , distance: Int ) {
123
- let possiblePaths = tspPaths ( allPermutations ( cities) )
124
- var bestPath : [ T ] = [ ]
125
- var minDistance : Int = Int . max
123
+ let possiblePaths = tspPaths ( allPermutations ( cities) ) // all potential paths
124
+ var bestPath : [ T ] = [ ] // shortest path by distance
125
+ var minDistance : Int = Int . max // distance of the shortest path
126
126
for path in possiblePaths {
127
- if path. count < 2 { continue }
127
+ if path. count < 2 { continue } // must be at least one city pair to calculate
128
128
var distance = 0
129
129
var last = path. first! // we know there is one becuase of above line
130
- for next in path [ 1 ..< path. count] {
130
+ for next in path [ 1 ..< path. count] { // add up all pair distances
131
131
distance += distances [ last] ![ next] !
132
132
last = next
133
133
}
134
- if distance < minDistance {
134
+ if distance < minDistance { // found a new best path
135
135
minDistance = distance
136
136
bestPath = path
137
137
}
0 commit comments