2013-11-03 144 views
0

我有一個2^n大小的int數組,我想檢查一個元素是否存在大於0.如果該元素存在,我想分割數組4,並檢查找到的元素的座標是否在數組的第1,第2,第3或第4象限中。在一個二維數組中搜索一個值的範圍

例如,如果在邏輯上在第一象限中存在元件它看起來像這樣:

如果array [] []> 0 & &座標的該行的範圍是0-(網格.length/2-1)& &該座標的列在0-(grid.length/2-1)的範圍內,然後執行一些操作。

我真的不知道如何檢查找到的元素的行和列索引,並存儲這些座標以在我的if語句中使用。幫幫我!

回答

0

您正在使用嵌套for循環,對嗎?而且,我猜測,你有一個像返回找到的元素的函數的東西?所以你需要一個函數返回找到的元素它的座標 - 或者只是座標,如果數組在這個函數之外是可用的。

是這樣的(僞):

for i from 0 to max X 
    for j from 0 to max Y 
     if array[i][j] > 0 
      return (array[i][j], i, j) # A tuple, or whatever - 
             # just some data structure for 
             # storing multiple things 
1

你的代碼應該是這樣的

for(int i = 0; i < array.length; i++){ 
    for(int j; j < array[i].length; j++){ 
     if(array[i][j] > 0){ 
      do some thing 
     } 
    } 
} 
0

當我明白你的問題,你有以下情況:鑑於之間0的整數k ,N(表示一個元素在單個dim數組中的位置)找到二維數組中相應單元格的座標,即找到x(i,j),其中x具有R行和C列。

Example (rows R=3 and Columns C=4) 

0 1 2 3 
4 5 6 7 
8 9 10 11 

Given k=6 Then i=1, j=2 
Given k=11 Then i=2, j=3 

Given k, you can find i, j as follows: 

i=Int(k/c) //Row number (0-based) 

j=k%c // Column number - (0-based) obtained by the remainder of dividing k by c