-
Notifications
You must be signed in to change notification settings - Fork 0
/
eightqueens.py
130 lines (88 loc) · 2.17 KB
/
eightqueens.py
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
from geneticsalgorithm import ga
import numpy as np
# population
population_size = 30
population = np.array([ np.random.choice(list(range(8)), size = 8, replace=False) for i in range(population_size)])
# fitness
def fitness(invididual):
conflicts = 0
#conflicts counter
for li,ci in enumerate(invididual):
for lj,cj in enumerate(invididual):
#not same line
if li != lj:
#same main diag
if (li - ci) == (lj - cj):
conflicts += 1
elif (li + ci) == (lj + cj):
conflicts += 1
return conflicts
# crossover_prob
crossover_prob = 1
# mutation_prob
mutation_prob = 0.5
# crossover
def crossover(ind1, ind2):
cut = np.random.randint(1,len(ind1)-4)
ref = np.zeros(len(ind1)) != 0
new_ind = np.zeros(len(ind1)) - 1
i = 0
i1 = 0
i2 = 0
acc = 0
while i < len(ind1):
if i < cut or acc == 4:
if not ref[ind1[i1]]:
new_ind[i] = ind1[i1]
ref[ind1[i1]] = True
i += 1
i1 += 1
else:
i1 += 1
elif not ref[ind2[i2]] and acc < 4:
new_ind[i] = ind2[i2]
ref[ind2[i2]] = True
i2 +=1
i +=1
acc +=1
else:
i2 += 1
return [new_ind]
# mutation
def mutation(ind):
perm = np.random.choice(list(range(8)),size=2,replace= False)
temp = ind[perm[0]]
ind[perm[0]] = ind[perm[1]]
ind[perm[1]] = temp
return ind
# objective
objective = "minimize"
# max_epochs
max_epochs = 1000
# generational
generational = False
# mutation_extra_individual
mutation_extra_individual = True
# stop_if_reachs
stop_if_reachs = 0
# offspring_size
#45% da population
offsprings = int(population_size * 0.3)
# progenitors_amount
progenitors_amount = 10
# elitist
elitist = False
ga(population = population,
fitness = fitness,
crossover_prob = crossover_prob,
mutation_prob = mutation_prob,
crossover = crossover,
mutation = mutation,
objective = objective,
max_epochs = max_epochs,
generational = generational,
mutation_extra_individual = mutation_extra_individual,
stop_if_reachs = stop_if_reachs,
offsprings = offsprings,
progenitors_amount = progenitors_amount,
elitist = elitist)