Search code examples
iphoneios4nsarrayios5

use NSArray to get minimum and maximum values of objects


I have an NSArray of double objects.... I currently I have a for loop to go through the NSArray and average them. I am looking for a way to determine the minimum and maximum values in the NSArray and have no idea where to start... below is the current code I have to get the average.

NSArray *TheArray = [[NSArray alloc] initWithArray:self.fetchedResultsController.fetchedObjects];
    int TotalVisitors = [TheArray count];
    double aveRatingSacore = 0;

for (int i = 0; i < TotalVisitors; i++)
        {
            Visitor *object = [TheArray objectAtIndex:i];
            double two = [object.rating doubleValue];
            aveRatingSacore = aveRatingSacore + two;
        }

        aveRatingSacore = aveRatingSacore/TotalVisitors;

Any help, suggestions or code would be greatly appreciated.


Solution

  • Setup two doubles, one for min, one for max. Then in each iteration, set each to the min/max of the existing min/max and the current object in the iteration.

    double theMin;
    double theMax;
    BOOL firstTime = YES;
    for(Visitor *object in TheArray) {
      if(firstTime) {
        theMin = theMax = [object.rating doubleValue];
        firstTime = NO;
        coninue;
      }
      theMin = fmin(theMin, [object.rating doubleValue]);
      theMax = fmax(theMax, [object.rating doubleValue]);
    }
    

    The firstTime bit is only to avoid false-positives involving zero.