Python中nQueens问题中的碰撞计数

2024-06-15 04:42:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我开始为Ai开发python,但遇到了一些问题:

我有个n皇后问题 here is a detailed explanation of the problem

fitness函数接收以下形式的数组:

decoded =  [3, 1, 2, 5 ... n]

其中元素对应于X坐标,索引对应于Y坐标 i、 e.从上述示例中获取坐标:

^{pr2}$

所以我有一个适应度函数,它接收一个与第一个例子相似的数组 var记录从最大碰撞次数n*(n-1)开始,并随着每次发现的碰撞而减少

^{3}$

因此,一个最佳情况下的世界返回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


Tags: of函数truereturnifhereischeck
1条回答
网友
1楼 · 发布于 2024-06-15 04:42:12
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 == dy

相关问题 更多 >