18
18
19
19
#if os(OSX)
20
20
import Foundation
21
+ import Cocoa
21
22
#elseif os(Linux)
22
23
import Glibc
23
24
#endif
24
25
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
-
36
26
protocol Clonable {
37
27
init ( current: Self )
38
28
}
@@ -96,8 +86,8 @@ extension Point {
96
86
static func <-> ( left: Point , right: Point ) -> Double {
97
87
let xDistance = ( left. x - right. x)
98
88
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 ( )
101
91
}
102
92
}
103
93
@@ -128,15 +118,6 @@ extension Tour {
128
118
self [ a] = cpos2
129
119
self [ b] = cpos1
130
120
}
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
- }
140
121
141
122
func currentEnergy( ) -> Double {
142
123
if self . energy == 0 {
@@ -155,7 +136,10 @@ extension Tour {
155
136
}
156
137
return self . energy
157
138
}
158
-
139
+
140
+ func shuffle( ) {
141
+ self . shuffle ( )
142
+ }
159
143
}
160
144
161
145
// MARK: - subscript to manipulate elements of Tour.
@@ -180,13 +164,13 @@ func SimulatedAnnealing<T: SAObject>(initial: T, temperature: Double, coolingRat
180
164
181
165
while temp > 1 {
182
166
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)
185
169
newSolution. randSwap ( a: pos1, b: pos2)
186
170
let currentEnergy : Double = currentSolution. currentEnergy ( )
187
171
let newEnergy : Double = newSolution. currentEnergy ( )
188
172
189
- if acceptance ( currentEnergy, newEnergy, temp) > Double . random ( 0 , 1 ) {
173
+ if acceptance ( currentEnergy, newEnergy, temp) > Double . random ( in : 0 ..< 1 ) {
190
174
currentSolution = newSolution. clone ( )
191
175
}
192
176
if currentSolution. currentEnergy ( ) < bestSolution. currentEnergy ( ) {
0 commit comments