We got 2D array, arr (n)(n). e pick any index, and the task is to count min and max value of a surrounding elements [closed]

StackOverflow https://stackoverflow.com/questions/19431539

  •  01-07-2022
  •  | 
  •  

Question

We got 2D array, arr[n][n]. We pick any index, and the task is to count min and max value of a surrounding elements (at least 3 if it is in the corner, and 8 if it is somewhere in the middle). Don't ask you guys to solve it for me, but give an advice on how it is better to perform.

Was it helpful?

Solution 2

A version with reduced amount of iterations, fixed off-by-one error, more simple and answering the question about max/min finding.

// (x,y) is the center point;
// assert ( x>=0 && y>=0 && x<n && y<n );
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE, m = n-1;

for( int i = (x==0)? 0 : x-1, x_max = (x==m)? m : x+1; i <= x_max; i++ )
  for( int j = (y==0)? 0 : y-1, y_max = (y==m)? m : y+1; j <= y_max; j++ ) {
    if( arr[i][j] < min )
      min = arr[i][j];
    else if ( arr[i][j] > max )
      max = arr[i][j];
    }

// now you have the max/min values set

or, if you prefer a more verbose version without ternary operator (slower, but more readable for beginners):

// (x,y) is the center point
int x_min = x - 1, y_min = y - 1,
    x_max = x + 1, y_max = y + 1,
    min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
if ( x_min < 0 )
  x_min = 0;
if ( y_min < 0 )
  y_min = 0;
if ( x_max > n - 1 ) // you can set 'int m = n - 1;'
  x_max = n - 1;     // and use m here instead if you wish
if ( y_max > n - 1 )
  y_max = n - 1;

for( int i = x_min; i <= x_max; i++ )
  for( int j = y_min; j <= y_max; j++ ) {
    if( arr[i][j] < min )
      min = arr[i][j];
    else if ( arr[i][j] > max )
      max = arr[i][j];
    }

// now you have the max/min values set

OTHER TIPS

Given a position in your array (x, y) you need to visit each surrounding entry.

for ( int i = -1; i <= 1; i++ ) {
  for ( int j = -1; j <= 1; j++ ) {
    // Don't visit off-array locations.
    if ( inArray(x+i,y+j) ) {
      // Don't visit the center cell (you wanted the 8 surrounding cells).
      if ( i != 0 && j != 0 ) {
        check (x+i,y+j);
      }
    }
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top