Java loop over half an array

I would like to iterate over half an array in Java; this is because the matrix will be completely symmetrical. If I loop, I drop the columns i and j of the rows, every time I perform an operation with the matrix [i] [j], I will perform the same operation with the matrix [j] [i]. I would have to save time by not looping half the matrix. Any ideas on an easy way to do this?

+4
source share
4 answers

If you are trying to get a triangle:

for(int i=0; i<array.length; i++){ for(int j=0; j<=i; j++){ ..do stuff... } } 
+7
source
 for (i = 0;i < size; ++i) { for (j = 0; j < i; ++j) { result = do_operation(i,j); matrix[i][j] = result; matrix[j][i] = result ; } } 

Thus, you call the do_operation operation method only once for each pair.

0
source
 for(int i = 0; i<array.length; i++){ for(int j = 0; j < array[i].length - i; j++){ // operation here } } 
0
source

Maybe I missed something here, but let me say that you have two arrays representing your rows and columns, respectively, and assuming that it is symmetrical (as you say):

 int dimension = rows.Length; for(int i=0; i<dimension; i++) { int j = (dimension-1) - i; //need dimension-1 to avoid an off-by-one error DoSomething(matrix[i][j]); DoSomehting(matrix[j][i]); } 

This solution has the advantage of performing at run time only to repeat one cycle, not two.

0
source

All Articles