File tree Expand file tree Collapse file tree 1 file changed +6
-6
lines changed
Classic Computer Science Problems in Swift.playground/Pages/Chapter 8.xcplaygroundpage Expand file tree Collapse file tree 1 file changed +6
-6
lines changed Original file line number Diff line number Diff line change @@ -120,18 +120,18 @@ func tspPaths<T>(_ permutations: [[T]]) -> [[T]] {
120120print ( tspPaths ( testPerms) )
121121
122122func 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
126126 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
128128 var distance = 0
129129 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
131131 distance += distances [ last] ![ next] !
132132 last = next
133133 }
134- if distance < minDistance {
134+ if distance < minDistance { // found a new best path
135135 minDistance = distance
136136 bestPath = path
137137 }
You can’t perform that action at this time.
0 commit comments