You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: Genetic/README.markdown
+48-1Lines changed: 48 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -188,4 +188,51 @@ The above is used to generate a completely new generation based on the current g
188
188
189
189
## Putting it all together -- Running the Genetic Algorithm
190
190
191
-
We now have all the methods we need to kick off the process. What is missing a `main()` function that loops though each generation of the GA.
191
+
We now have all the functions we need to kick off the algorthim. Let's start from the beginning, first we need a random population to serve as a starting point. We will also initialize a fittest variable to hold the fittest individual, we will initialize it with the first individual of our random population.
192
+
193
+
```swift
194
+
var population:[[UInt8]] =randomPopulation(from: lex, populationSize: POP_SIZE, dnaSize: DNA_SIZE)
195
+
var fittest = population[0]
196
+
```
197
+
198
+
Now for the meat, the remainder of the code will take place in the generation loop, running once for every generation:
199
+
200
+
```swift
201
+
for generation in0...GENERATIONS {
202
+
// run
203
+
}
204
+
```
205
+
206
+
Now, for each individual in the population, we need to calculate its fitness and weighted value. For weighted choice we store the fitness as a percent `1 / fitness`.
207
+
208
+
```swift
209
+
var weightedPopulation = [(item:[UInt8], weight:Double)]()
210
+
211
+
for individual in population {
212
+
let fitnessValue =calculateFitness(dna: individual, optimal: OPTIMAL)
213
+
let pair = ( individual, fitnessValue ==0?1.0:1.0/Double( fitnessValue ) )
214
+
weightedPopulation.append(pair)
215
+
}
216
+
```
217
+
218
+
To understand weighted choice, let walk though a smaller example, let's say we have the following population, where 0 is the best fitness:
0 commit comments