簡體   English   中英

確定 x/y 網格索引的算法

[英]Algorithm to determine index of x/y grid

好的,我知道此操作還有另一個名稱,但如果我知道,我會在谷歌中搜索並找到正確的算法。 我希望你能從下圖中理解我的意圖:

好的,假設我們有一個網格,例如 3x3 對象 (.)

...
...
...

這些對象中的每一個都有索引,從 0 開始,以 8 結束

012
345
678

然后讓我們使用以下循環:

w = 0; h = 0;
go :
w = 0;
for(; w<grid.width; w++)
{
    statuses[w][h] = isActor(CORESPONDENT_INDEX_GOES_HERE);
    if(w == grid.width-1 && h != grid.height-1)
    {
        h += 1;
        goto go;
    }
}

isActor是一個 function,它返回當前對象的狀態,它需要正確的索引。

我應該放什么代替CORESPONDENT_INDEX_GOES_HERE 如果我使用w*h它不起作用,我知道為什么。 它不會返回正確的索引。

什么是正確的算法?

如hk6279所述,請使用h * grid.width + w

這稱為“光柵掃描”。 不幸的是,沒有搜索“光柵”可以揭示該公式。

這表示多維數組。 在您的情況下,它是一個3維數組。

該數組定義為arr [3] [3]。 假定索引計算如下:

      Column0 Column1 Column2

Row0    0       1      2
Row1    3       4      5
Row2    6       7      8

The index to access each of the values is:

Row0
arr[0][0] = 0
arr[0][1] = 1
arr[0][2] = 2

Row1
arr[1][0] = 3
arr[1][1] = 4
arr[1][2] = 5

Row2
arr[2][0] = 6
arr[2][1] = 7
arr[2][2] = 8

我想將您的代碼重寫為如下形式:

int gridsize = grid.width * grid.height; // be sure it doesn't overflow here
int index;
for (index = 0; index < gridsize; index++)
{
    int w = index % grid.width;
    int h = index / grid.width;
    statuses[w][h] = isObject(PIXEL.name, CORESPONDENT_INDEX_GOES_HERE);
}

index的變量可以在C11for循環內定義:

for (int index = 0; index < gridsize; index++)

請參閱commons 中的實時示例

/* gives position of 2D point (ix,iy) in 1D array  ; uses also global variable iWidth */
unsigned int Give_i (unsigned int ix, unsigned int iy)
{
  return ix + iy * iWidth;
}

您可以從 terra(C++ 代碼)或光柵(R 代碼)package 查看/使用cellFromRowCol

library(terra)
r <- rast(ncol=3, nrow=3)
cellFromRowCol(r, 2, 2) - 1
#[1] 4

(注意 -1 因為 R 索引從 1 開始,而您希望從 0 開始)。

還有

 cellFromXY(r, cbind(1,1))

這適用於 (x, y)坐標,而不適用於行/列數。

這些函數是矢量化的,因此您可能不需要循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM