计算Python中的n-Queens问题中的冲突

时间:2018-09-30 04:39:49

标签: python matrix genetic-algorithm n-queens

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

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

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

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

它调用的辅助函数检查给定的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

1 个答案:

答案 0 :(得分:0)

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