Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java loop over half of array

Tags:

java

loops

matrix

I would like to loop over half of an array in Java; this is because the matrix will be completely symmetric. If I loop throw i columns and j rows, every time I do an operation of matrix[i][j] I will do the exact same operation to matrix[j][i]. I should be able to save time by not looping over half of the matrix. Any ideas on the easiest way to do this?

like image 228
Nate Glenn Avatar asked Dec 27 '22 16:12

Nate Glenn


2 Answers

If you're trying to get a triangle:

for(int i=0; i<array.length; i++){
  for(int j=0; j<=i; j++){
    ..do stuff...
  }
}
like image 119
Andrea Avatar answered Jan 08 '23 20:01

Andrea


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 ;
 }
}

So you invoke the operation method do_operation only once for each pair.

like image 41
Basanth Roy Avatar answered Jan 08 '23 21:01

Basanth Roy