0

我正在开发一个随机地牢生成器,只是为了好玩/作为学习一些新事物的辅助项目。我编写了一个函数,它为任何给定的单元格返回一个整数哈希值,它为您提供有关它应该是什么类型的游戏对象的信息。即如果它是一堵墙,面对什么方向,它是不是一个角落,等等。这是功能当前的样子。

    private int CellHashValue(int xIndex, int yIndex, char centerTile)
    {
        int hashValue = 0;
        if (dungeon2DArray[xIndex - 1, yIndex + 1] == centerTile)
        {
            hashValue += 1;
        }
        if (dungeon2DArray[xIndex, yIndex + 1] == centerTile)
        {
            hashValue += 2;
        }
        if (dungeon2DArray[xIndex + 1, yIndex + 1] == centerTile)
        {
            hashValue += 4;
        }
        if (dungeon2DArray[xIndex - 1, yIndex] == centerTile)
        {
            hashValue += 8;
        }
        if (dungeon2DArray[xIndex + 1, yIndex] == centerTile)
        {
            hashValue += 16;
        }
        if (dungeon2DArray[xIndex - 1, yIndex - 1] == centerTile)
        {
            hashValue += 32;
        }
        if (dungeon2DArray[xIndex, yIndex - 1] == centerTile)
        {
            hashValue += 64;
        }
        if (dungeon2DArray[xIndex + 1, yIndex - 1] == centerTile)
        {
            hashValue += 128;
        }
        return hashValue;
    }

我的问题是,是否有一种更有效、更快的方法来进行这些我可能没有想到的检查?地牢数组的大小范围从 100x100 到 1000x1000,尽管该函数不会在每个单元格上调用。我有一个单独的列表,其中包含房间,并且我迭代以实例化对象的每个方向都有开始和结束索引。

4

2 回答 2

2

你所做的本质上是应用一种卷积形式。如果没有更多关于如何调用您的方法或如何使用返回的哈希值的上下文,您所做的似乎接近于迭代 3x3 网格的最有效方法。假设您的 dungeon2dArray 是一个 char[][] 并且是全局的,我认为这是更清晰和更简洁的内容(您必须根据迭代顺序调整如何解释结果总和)。

private int CellHashValue(int x, int y) {
    int hashSum = 0;   // Hash sum to return
    int hashValue = 1; // Increases as power of 2 (1,2,4,8,...128)
    char centerTile = dungeon2DArray[x, y]; // Cache center tile

    for (int r = -1; r <= 1; r++) {
        for (int c = -1; c <= 1; c++) {
            if (r == 0 && c == 0) continue; // Skip center tile
            if (dungeon2DArray[x + c, y + r] == centerTile) {
                hashSum += hashValue;
            }
            hashValue *= 2; // Next power of two
            //could also bit shift here instead 
            // hashValue <<= 1
        }
    }
    return hashSum;
}

注意:此方法不进行任何边界检查,因此如果 x 或 y 索引沿边缘,则索引将失败。

每个数组访问都是 O(1) 并且遍历整个地牢数组是 O(n^2),因此获得更好效率的唯一方法是组合每个单元格的方法调用,但这仍然只是一个常数因素,所以效率并不高,但取决于计算可以稍微提高性能。

于 2018-02-19T20:44:42.793 回答
1

由于您使用数组来构建地图,因此由于直接访问,访问时间是恒定的。因此,检查每个数组索引的过程很快。

有几件小事可以加速这个功能。

  1. if返回相应语句中的 hashValue 。这将删除几行代码。
  2. 通过删除hashValue变量并返回硬编码值,将从进程中删除变量初始化。这比看起来更重要。创建和删除一个对象需要时间,在规模化时需要很多时间。
  3. xIndex并且yIndex可以对对象进行全局设置。小心实施这个想法。由于 xIndex 和 yIndex 在检查特定条件时不会更改,因此可以将它们设置为对象内的全局。这减少了传入的参数数量。由于 Java 不通过引用传递,因此创建了一个大小相等的对象并将其传递给函数。简单int不会对速度产生太大影响,但如果您有一个包含许多变量的对象,则需要更多时间来构建另一个同等价值的对象。
  4. 每个检查都可以移动到一个单独的函数中。这主要有助于以后的可读性和调试。有一些速度优势,但它们取决于项目。通过观察对象是如何初始化/操作的,通常可以强制某些条件为真。当不需要检查逻辑并且无需检查即可得出结论时,则需要更少的时间。

只是一些想法。如果您有时间研究,第 2 点和第 3 点使用的概念来自low latency/high frequency. 另外,请注意,其中一些概念并不被认为是最佳实践。

于 2018-02-19T19:05:08.467 回答