FrankZp
FrankZp

Reputation: 2042

Objective C: Fastest way for conditional check between objects of an Array

I have an NSArray of custom objects. Those objects have a property price which I want to compare with the price of all other objects in the array. If the price difference to another objects' price is less then 100, there should be a method call.

NSArray products (
  {
      name = "Product A";
      price = "1299.50";
  },
  {
      name = "Product B";
      price = "999.90";
  },
  {
      name = "Product C";
      price = "1249.00";
  },
  {
      name = "Product D";
      price = "1899.50";
  }
)

=> Product A and Product C have a price difference from < 100 and therefore a method closePrices:(NSArray *)objectsWhichAreClose should be called passing the objects which are close.

I wonder which is the most efficient way to achieve this?

Upvotes: 0

Views: 167

Answers (2)

Mohannad A. Hassan
Mohannad A. Hassan

Reputation: 1648

Simple and fast solution is to sort then search sequentially.

Sorting can be achieved in O(N logN). You can compare each item in the array with one following it. If the difference is less than 100, perform the required method.

If you need to detect all close objects, you can keep iterating till you find an object with difference > 100.

for(int i = 0; i < sortedProducts.count; i++) {
    for(int j = i + 1; j < sortedProducts.count; j++) {
        if(sortedProjects[j].price - sortedProjects[i].price <= 100) {
            [self callMethod];
        }
        else {
            break;
        }
    }
}

This loop actually has running time of O(N^2). But, depending on the nature of the data, it can achieve better time. This can happen if the pairs of close numbers are a small subset of all possible pairs. If this is not the case, i.e. many objects are close to each other, then I advise you to implement @DrDev's solution. It's simpler in that case.

Upvotes: 1

DrDev
DrDev

Reputation: 442

for (int i=0;i<[products count];i++){
  for (int j=0;j<[products count];j++){
  if (i != j){
  MyClass *obj = (MyClass*)[products objectAtIndex:i];
  MyClass *obj2 = (MyClass*)[products objectAtIndex:j];

  if (fabs(obj.price - obj2.price) < 100){
     [self closePrices];
   }
 }

}
}

Note: Dont forget to include math for fabs()

Upvotes: 1

Related Questions