1818
1919#if os(OSX)
2020 import Foundation
21+ import Cocoa
2122#elseif os(Linux)
2223 import Glibc
2324#endif
2425
25- public extension Double {
26-
27- public static func random( _ lower: Double , _ upper: Double ) -> Double {
28- #if os(OSX)
29- return ( Double ( arc4random ( ) ) / 0xFFFFFFFF ) * ( upper - lower) + lower
30- #elseif os(Linux)
31- return ( Double ( random ( ) ) / 0xFFFFFFFF ) * ( upper - lower) + lower
32- #endif
33- }
34- }
35-
3626protocol Clonable {
3727 init ( current: Self )
3828}
@@ -96,8 +86,8 @@ extension Point {
9686 static func <-> ( left: Point , right: Point ) -> Double {
9787 let xDistance = ( left. x - right. x)
9888 let yDistance = ( left. y - right. y)
99-
100- return Double ( sqrt ( Double ( ( xDistance * xDistance) + ( yDistance * yDistance) ) ) )
89+
90+ return Double ( ( xDistance * xDistance) + ( yDistance * yDistance) ) . squareRoot ( )
10191 }
10292}
10393
@@ -128,15 +118,6 @@ extension Tour {
128118 self [ a] = cpos2
129119 self [ b] = cpos1
130120 }
131-
132- func shuffle( ) {
133- for i in stride ( from: self . count - 1 , through: 1 , by: - 1 ) {
134- let j = Int ( arc4random ( ) ) % ( i + 1 )
135- if i != j {
136- swap ( & self . tour [ i] , & self . tour [ j] )
137- }
138- }
139- }
140121
141122 func currentEnergy( ) -> Double {
142123 if self . energy == 0 {
@@ -155,7 +136,10 @@ extension Tour {
155136 }
156137 return self . energy
157138 }
158-
139+
140+ func shuffle( ) {
141+ self . shuffle ( )
142+ }
159143}
160144
161145// MARK: - subscript to manipulate elements of Tour.
@@ -180,13 +164,13 @@ func SimulatedAnnealing<T: SAObject>(initial: T, temperature: Double, coolingRat
180164
181165 while temp > 1 {
182166 let newSolution : T = currentSolution. clone ( )
183- let pos1 : Int = Int ( arc4random_uniform ( UInt32 ( newSolution. count) ) )
184- let pos2 : Int = Int ( arc4random_uniform ( UInt32 ( newSolution. count) ) )
167+ let pos1 : Int = Int . random ( in : 0 ..< newSolution. count)
168+ let pos2 : Int = Int . random ( in : 0 ..< newSolution. count)
185169 newSolution. randSwap ( a: pos1, b: pos2)
186170 let currentEnergy : Double = currentSolution. currentEnergy ( )
187171 let newEnergy : Double = newSolution. currentEnergy ( )
188172
189- if acceptance ( currentEnergy, newEnergy, temp) > Double . random ( 0 , 1 ) {
173+ if acceptance ( currentEnergy, newEnergy, temp) > Double . random ( in : 0 ..< 1 ) {
190174 currentSolution = newSolution. clone ( )
191175 }
192176 if currentSolution. currentEnergy ( ) < bestSolution. currentEnergy ( ) {
0 commit comments