python - 如何更有效地检查游戏板上的条纹?

标签 python algorithm performance

下面的函数像这样接收一个二维数组。

[['.', '.', '.', '.', '.', '.', '.'],
 ['.', '.', '.', '.', '.', '.', '.'],
 ['.', '.', 'y', '.', '.', '.', '.'],
 ['.', '.', 'y', '.', 'r', '.', 'y'],
 ['.', 'r', 'r', 'y', 'r', 'y', 'r'],
 ['.', 'r', 'y', 'y', 'r', 'r', 'y']]

该函数的目的是计算我的二维数组中存在的指定大小的“条纹”的数量。条纹被定义为水平、垂直或对角线排列的连续标记线。

以下示例算作 1 次大小为 2 的连胜。

[['.', '.', '.', '.', '.', '.', '.'],
 ['.', '.', '.', '.', '.', '.', '.'],
 ['.', '.', '.', '.', '.', '.', '.'],
 ['.', '.', '.', '.', '.', '.', '.'],
 ['.', '.', 'r', '.', '.', '.', '.'],
 ['.', 'r', '.', '.', '.', '.', '.']]

以下代码段是我的蛮力解决方案,它遍历了棋盘的每个组合。是否有更高效的解决方案/算法可供我使用?

def streaks(num_repeats, board, player_color):    
    reduced_range = num_repeats - 1
    list_idx_offsets = list(range(0, num_repeats))
    counter = 0
    # Checks rows
    for col in range(0, COLUMN_COUNT - reduced_range):
        for row in range(0, ROW_COUNT):
            list_results = []
            for idx in list_idx_offsets:
                list_results.append(board[row][col + idx])
            # If the list is identical and the player is in the list, then increment counter
            if list_els_identical(list_results) and player_color in list_results:
                counter += 1
    # Checks columns
    for col in range(0, COLUMN_COUNT):
        for row in range(0, ROW_COUNT - reduced_range):
            list_results = []
            for idx in list_idx_offsets:
                list_results.append(board[row + idx][col])
            if list_els_identical(list_results) and player_color in list_results:
                counter += 1
    # Check diagonals positive
    for col in range(0, COLUMN_COUNT - reduced_range):
        for row in range(0, ROW_COUNT - reduced_range):
            list_results = []
            for idx in list_idx_offsets:
                list_results.append(board[row + idx][col + idx])
            if list_els_identical(list_results) and player_color in list_results:
                counter += 1
    # Check diagonals negative
    for col in range(0, COLUMN_COUNT - reduced_range):
        for row in range(reduced_range, ROW_COUNT):
            list_results = []
            for idx in list_idx_offsets:
                list_results.append(board[row - idx][col + idx])
            if list_els_identical(list_results) and player_color in list_results:
                counter += 1
    return counter

最佳答案

如果只有 x 件,连续检查 x 件,因为不能再多了,然后停止。这比检查每个组合要快。

关于python - 如何更有效地检查游戏板上的条纹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55485557/

相关文章:

python - 无法有效删除 ‘v’ 之前的字符串或删除 v 及之后的字符串

python - 部分定义 scikit-learn K-Means 聚类的初始质心

algorithm - 创建动态编程算法以使用 tetranacci 数计算斐波那契数列

c - 合并给定空间中的元素数组

c++ - 有效地找到不在大小为 40、400 或 4000 的集合中的整数

python - Numpy:Row Wise Unique 元素

css - 提高转换为 View 时位图图像解码的性能

performance - 在 PostgreSQL 上首次加载时查询运行速度非常慢

c++ - 从接口(interface)虚拟继承的成本

python - .withColumn和.agg在pyspark中并行计算吗?