forked from kodecocodes/swift-algorithm-club
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gen.swift
148 lines (108 loc) · 4.42 KB
/
gen.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
//: Playground - noun: a place where people can play
import Foundation
extension String {
var unicodeArray: [UInt8] {
return [UInt8](self.utf8)
}
}
let lex: [UInt8] = " !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~".unicodeArray
// This is the end goal and what we will be using to rate fitness. In the real world this will not exist
let OPTIMAL:[UInt8] = "Hello, World".unicodeArray
// The length of the string in our population. Organisms need to be similar
let DNA_SIZE = OPTIMAL.count
// size of each generation
let POP_SIZE = 50
// max number of generations, script will stop when it reach 5000 if the optimal value is not found
let MAX_GENERATIONS = 5000
// The chance in which a random nucleotide can mutate (1/n)
let MUTATION_CHANCE = 100
func randomChar(from lexicon: [UInt8]) -> UInt8 {
let len = UInt32(lexicon.count-1)
let rand = Int(arc4random_uniform(len))
return lexicon[rand]
}
func randomPopulation(from lexicon: [UInt8], populationSize: Int, dnaSize: Int) -> [[UInt8]] {
var pop = [[UInt8]]()
(0..<populationSize).forEach { _ in
var dna = [UInt8]()
(0..<dnaSize).forEach { _ in
let char = randomChar(from: lexicon)
dna.append(char)
}
pop.append(dna)
}
return pop
}
func calculateFitness(dna:[UInt8], optimal:[UInt8]) -> Int {
var fitness = 0
(0...dna.count-1).forEach { c in
fitness += abs(Int(dna[c]) - Int(optimal[c]))
}
return fitness
}
func weightedChoice(items:[(dna:[UInt8], weight:Double)]) -> (dna:[UInt8], weight:Double) {
let total = items.reduce(0.0) { return $0 + $1.weight}
var n = Double(arc4random_uniform(UInt32(total * 1000000.0))) / 1000000.0
for item in items {
if n < item.weight {
return item
}
n = n - item.weight
}
return items[1]
}
func mutate(lexicon: [UInt8], dna:[UInt8], mutationChance:Int) -> [UInt8] {
var outputDna = dna
(0..<dna.count).forEach { i in
let rand = Int(arc4random_uniform(UInt32(mutationChance)))
if rand == 1 {
outputDna[i] = randomChar(from: lexicon)
}
}
return outputDna
}
func crossover(dna1:[UInt8], dna2:[UInt8], dnaSize:Int) -> [UInt8] {
let pos = Int(arc4random_uniform(UInt32(dnaSize-1)))
let dna1Index1 = dna1.index(dna1.startIndex, offsetBy: pos)
let dna2Index1 = dna2.index(dna2.startIndex, offsetBy: pos)
return [UInt8](dna1.prefix(upTo: dna1Index1) + dna2.suffix(from: dna2Index1))
}
func main() {
// generate the starting random population
var population:[[UInt8]] = randomPopulation(from: lex, populationSize: POP_SIZE, dnaSize: DNA_SIZE)
// print("population: \(population), dnaSize: \(DNA_SIZE) ")
var fittest = [UInt8]()
for generation in 0...MAX_GENERATIONS {
var weightedPopulation = [(dna:[UInt8], weight:Double)]()
// calulcated the fitness of each individual in the population
// and add it to the weight population (weighted = 1.0/fitness)
for individual in population {
let fitnessValue = calculateFitness(dna: individual, optimal: OPTIMAL)
let pair = ( individual, fitnessValue == 0 ? 1.0 : Double(100/POP_SIZE)/Double( fitnessValue ) )
weightedPopulation.append(pair)
}
population = []
// create a new generation using the individuals in the origional population
(0...POP_SIZE).forEach { _ in
let ind1 = weightedChoice(items: weightedPopulation)
let ind2 = weightedChoice(items: weightedPopulation)
let offspring = crossover(dna1: ind1.dna, dna2: ind2.dna, dnaSize: DNA_SIZE)
// append to the population and mutate
population.append(mutate(lexicon: lex, dna: offspring, mutationChance: MUTATION_CHANCE))
}
fittest = population[0]
var minFitness = calculateFitness(dna: fittest, optimal: OPTIMAL)
// parse the population for the fittest string
population.forEach { indv in
let indvFitness = calculateFitness(dna: indv, optimal: OPTIMAL)
if indvFitness < minFitness {
fittest = indv
minFitness = indvFitness
}
}
if minFitness == 0 { break; }
print("\(generation): \(String(bytes: fittest, encoding: .utf8)!)")
}
print("fittest string: \(String(bytes: fittest, encoding: .utf8)!)")
}
main()