2013-11-03 84 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