-
Notifications
You must be signed in to change notification settings - Fork 6
/
Nqueen.py
184 lines (141 loc) · 5.13 KB
/
Nqueen.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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# Mahdi Hassanzadeh
from operator import indexOf
import random
# Making random chromosomes
def random_chromosome(size):
return [random.randint(0, size - 1) for _ in range(size)]
# Calculating fitness
def fitness(chromosome, maxFitness):
horizontal_collisions = (
sum([chromosome.count(queen) - 1 for queen in chromosome]) / 2
)
diagonal_collisions = 0
n = len(chromosome)
left_diagonal = [0] * (2 * n - 1)
right_diagonal = [0] * (2 * n - 1)
for i in range(n):
left_diagonal[i + chromosome[i] - 1] += 1
right_diagonal[len(chromosome) - i + chromosome[i] - 2] += 1
diagonal_collisions = 0
for i in range(2 * n - 1):
counter = 0
if left_diagonal[i] > 1:
counter += left_diagonal[i] - 1
if right_diagonal[i] > 1:
counter += right_diagonal[i] - 1
diagonal_collisions += counter
# 28-(2+3)=23
return int(maxFitness - (horizontal_collisions + diagonal_collisions))
# Doing cross_over between two chromosomes
def crossover(x, y):
n = len(x)
child = [0] * n
for i in range(n):
c = random.randint(0, 1)
if c < 0.5:
child[i] = x[i]
else:
child[i] = y[i]
return child
# Randomly changing the value of a random index of a chromosome
def mutate(x):
n = len(x)
c = random.randint(0, n - 1)
m = random.randint(0, n - 1)
x[c] = m
return x
# Calculating probability
def probability(chromosome, maxFitness):
return fitness(chromosome, maxFitness) / maxFitness
# Roulette-wheel selection
def random_pick(population, probabilities):
populationWithProbabilty = zip(population, probabilities)
total = sum(w for c, w in populationWithProbabilty)
r = random.uniform(0, total)
upto = 0
for c, w in zip(population, probabilities):
if upto + w >= r:
return c
upto += w
assert False, "Shouldn't get here"
# Genetic algorithm
def genetic_queen(population, maxFitness):
mutation_probability = 0.1
new_population = []
sorted_population = []
probabilities = []
for n in population:
f = fitness(n, maxFitness)
probabilities.append(f / maxFitness)
sorted_population.append([f, n])
sorted_population.sort(reverse=True)
# Elitism
new_population.append(sorted_population[0][1]) # the best gen
new_population.append(sorted_population[-1][1]) # the worst gen
for i in range(len(population) - 2):
chromosome_1 = random_pick(population, probabilities)
chromosome_2 = random_pick(population, probabilities)
# Creating two new chromosomes from 2 chromosomes
child = crossover(chromosome_1, chromosome_2)
# Mutation
if random.random() < mutation_probability:
child = mutate(child)
new_population.append(child)
if fitness(child, maxFitness) == maxFitness:
break
return new_population
# prints given chromosome
def print_chromosome(chrom, maxFitness):
print(
"Chromosome = {}, Fitness = {}".format(str(chrom), fitness(chrom, maxFitness))
)
# prints given chromosome board
def print_board(chrom):
board = []
for x in range(nq):
board.append(["x"] * nq)
for i in range(nq):
board[chrom[i]][i] = "Q"
def print_board(board):
for row in board:
print(" ".join(row))
print()
print_board(board)
if __name__ == "__main__":
POPULATION_SIZE = 500
while True:
# say N = 8
nq = int(input("Please enter your desired number of queens (0 for exit): "))
if nq == 0:
break
maxFitness = (nq * (nq - 1)) / 2 # 8*7/2 = 28
population = [random_chromosome(nq) for _ in range(POPULATION_SIZE)]
generation = 1
while (
not maxFitness in [fitness(chrom, maxFitness) for chrom in population]
and generation < 200
):
population = genetic_queen(population, maxFitness)
if generation % 10 == 0:
print("=== Generation {} ===".format(generation))
print(
"Maximum Fitness = {}".format(
max([fitness(n, maxFitness) for n in population])
)
)
generation += 1
fitnessOfChromosomes = [fitness(chrom, maxFitness) for chrom in population]
bestChromosomes = population[
indexOf(fitnessOfChromosomes, max(fitnessOfChromosomes))
]
if maxFitness in fitnessOfChromosomes:
print("\nSolved in Generation {}!".format(generation - 1))
print_chromosome(bestChromosomes, maxFitness)
print_board(bestChromosomes)
else:
print(
"\nUnfortunately, we could't find the answer until generation {}. The best answer that the algorithm found was:".format(
generation - 1
)
)
print_board(bestChromosomes)