我开始为Ai开发python,我遇到了一些问题:
我有个n-女皇问题以下是对这个问题的详细解释
适应度函数接收表单的数组:
decoded = [3, 1, 2, 5 ... n]如果元素对应于X坐标,索引对应于Y坐标,即取上述例子中的坐标:
# [X, Y]
pairCoords = [[3,0], [1, 1], [2, 2], [5, 1], ... [n, z]]因此,我的适应度函数接收到一个类似于第一个示例var记录的数组,该数组从最大碰撞数n*(n-1)开始,并随着每次碰撞次数的减少而减少。
def fitness(self, decodedGenes):
record = self.numeroN * (self.numeroN-1)
for y in range(len(decodedGenes)):
if self.positionIsAtacking(decodedGenes, decodedGenes[y], y):
record = record - 1
return record因此,最佳情况世界返回n*(n-1),而最坏情况则返回0。
它调用的auxiliar函数检查给定的X和Y坐标,如果发生碰撞,返回它,但它不能工作
def positionIsAtacking(self, coords, X, Y):
for i in range(len(coords)):
# Check Y
if (coords[i] == Y):
return True
# Check Diagonals
if (coords[i] - Y == i - X):
return True
if (coords[i] - Y == X - i):
return True
return False我试过改变参数,但是我不知道该在哪里搜索,我认为第二个函数不起作用,或者y改变了x和y。
发布于 2018-10-01 00:36:36
def fitness(self, cromosoma):
record = self.numeroN * (self.numeroN - 1)
for row in range(len(board)):
decodedGenes.append(self.decodeGene(board[row]))
for y in range(len(decodedGenes)):
x = decodedGenes[y]
record = record - self.collisions(decodedGenes, x, y)
return record
def collisions(self, coords, X, Y):
board = []
r = 0
for i in range(len(coords)):
board.append([0] * self.numeroN)
for y in range(len(coords)):
board[y][coords[y]] = 1
for y in range(len(board)):
for x in range(len(board)):
# if has Queen and is not the same
if board[y][x] == 1 and y != Y:
# check x
if x == X:
r = r + 1
# check Diagonals
if self.crash_diagonal(x, y, X, Y):
r = r + 1
return r
def crash_diagonal(self, x1, y1, x2, y2):
dx = abs(x1 - x2)
dy = abs(y1 - y2)
return dx == dyhttps://stackoverflow.com/questions/52574679
复制相似问题