-
Notifications
You must be signed in to change notification settings - Fork 0
/
selection.jl
65 lines (45 loc) · 1.3 KB
/
selection.jl
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
include("crossover.jl")
function elitistSelection(elitePercent::Float64)
function selectionMethod(population::Vector{Entity}, crossFunc!::Function)
n = length(population)
eliteNumber = Int(trunc(elitePercent*n));
eliteNumber = eliteNumber + (n-eliteNumber)%2
elite = deepcopy(population[1:eliteNumber])
population = crossover!(population[eliteNumber+1:end], crossFunc!)
population = [population; elite]
return population
end
end
function findIdx(arr, x)
l::Int = 1;
r::Int = length(arr)
s = l + div(r-l,2)
idx = s
while l <= r
if x <= arr[s]
idx = s
r = s-1
else
l = s+1
end
s = l + div(r-l,2)
end
return idx
end
function rouletteWheelSelection()
function selectionMethod(population::Vector{Entity}, crossFunc!::Function)
n = length(population)
px = population .|> fitFunction
totalFit = sum(px)
px = px .|> (x)->x/totalFit
for i=2:length(px)
px[i] = px[i] + px[i-1]
end
for i=1:div(n,2)
idx1 = findIdx(px, rand())
idx2 = findIdx(px, rand())
crossFunc!(population[idx1], population[idx2])
end
return population
end
end