[英]Searching a 2D array for a range of values in java
I have a 2^n size int array and I want to check if an element exists that is greater than 0. If the element exists, I want to divide the array by 4 and check if the coordinates of the found element are in the 1st, 2nd, 3rd or 4th quadrant of the array. 我有一个2 ^ n大小的int数组,我想检查是否存在一个大于0的元素。如果该元素存在,我想将该数组除以4,并检查找到的元素的坐标是否在第1个,数组的第二,第三或第四象限。
For example, logically if the element exists in the first quadrant it would look something like this: 例如,从逻辑上讲,如果元素在第一象限中,它将看起来像这样:
If array[][] > 0 && the row of that coordinate is in the range 0-(grid.length/2-1) && the column of that coordinate is in the range 0-(grid.length/2-1) then do something. 如果array [] []> 0 &&,则该坐标的行在0-(grid.length / 2-1)范围内&&列的坐标在0-(grid.length / 2-1)范围内然后做点什么。
I'm really not sure how to check the row and column index of the found element and store those coordinates to use in my if statement. 我真的不确定如何检查找到的元素的行和列的索引,以及将那些坐标存储在我的if语句中。 Help!
救命!
your code should be look like this 您的代码应如下所示
for(int i = 0; i < array.length; i++){
for(int j; j < array[i].length; j++){
if(array[i][j] > 0){
do some thing
}
}
}
You're using a nested for
loop, right? 您正在使用嵌套的
for
循环,对吧? And, I'm guessing, you have a something like a function which returns the found element? 而且,我猜想,您有类似返回所找到元素的函数的功能吗? So you need a function which returns the found element and its coordinates - or just the coordinates, if the array is available outside of this function.
因此,你需要它返回发现的元素及其坐标的功能-或者只是坐标,如果阵列是这个功能的使用之外。
Something like this (pseudocode): 这样的东西(伪代码):
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
As I understand your question, you have the following case: Given an integer k between 0, N (representing the position of an element in a single dim. array) find the coordinates of the corresponding cell in 2-d array, ie find x(i,j) where x has R rows and C columns. 据我了解您的问题,您遇到以下情况:给定一个介于0和N之间的整数k,N(代表一个尺寸数组中元素的位置)在2-d数组中找到相应单元格的坐标,即找到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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.