tags:

views:

420

answers:

6

How can I get the max and min value of array without calling other method?

Public triangles{
   for (Polygon p: triangles){
      int [] x = p.xpoints;
      int [] y = p.ypoints;
   }
   // I dont know how to get the max and min of array X and Y since both array are declared inside the loop.

}
A: 

Loop over the array in a nested loop.

Pete Kirkham
+2  A: 

As that code is written, you can't do anything with the x and y variables outside the scope of the loop, since they're not defined outside.

If you need to do more per-triangle processing, as it sounds, you should probably do that inside the loop.

unwind
+4  A: 
Public triangles{
  for (Polygon p: triangles){
    int [] x = p.xpoints;
    int [] y = p.ypoints;
    int maxX = x[0];
    int minX = x[0];
    int maxY = y[0];
    int minY = y[0];
    for(int i=1; i<x.length; i++){
      if(x[i]>maxX){
        maxX = x[i];
      }
      if(x[i]<minX){
        minX = x[i];
      }
      if(y[i]>maxY){
        maxY = y[i];
      }
      if(y[i]<minY){
        minY = y[i];
      }
    }
  }
}
Marius
Thanks for the code. This code solved my problem :-)
Jac
A: 

min = int.MaxValue; max = int.MinValue;

        for(int i=0;i<array.Length;i++)
        {
            min = min > array[i] ? array[i] : min ;
            max = max < array[i] ? array[i] : max ;
        }
Mehran
calling it a function doesn't really get around the arbitrary 'not calling other method' requirement.
Pete Kirkham
+1  A: 

It seems to me that you lack basic knowledge and understanding of arrays so you better of reading the Sun Tutorial

In general what you do is set the first element in the array to be the min (or max) and then iterate over the array comparing each element with the current minimum and set accordingly. e.g.

    int min = this.array[0];
    for(int current = 1; current < array.length; current++){
        min = (this.array[current] < min) ? array[current] : min; 
    }

In case you want to compare objects you would usually implement the Comparator interface which when used with Collections#sort can give you the min/max.

Although the first method works, depending on the number of elements your array has you are better of using a Sorting Algorithm to handle performance issues.

Cue
A: 

//import java.util.Arrays;

int xmin, ymin, xmax, ymax;

Arrays.sort(x);
Arrays.sort(y);

xmin = x[0];
xmax = x[x.length-1];

ymin = y[0];
ymax = y[y.length-1];

//This code is straight forward..

Suneel