0

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?

1
  • A plain sort + a loop should be pretty fast, and simple compared to most other alternatives. Commented Jun 18, 2013 at 13:47

2 Answers 2

1
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()

2
  • Wouldn't it be faster/more efficient with fast enumeration?
    – FrankZp
    Commented Jun 19, 2013 at 7:05
  • Yes indeed, but this is a very small loop... Not gna feel the difference. Anyway you can do it like that too: for(MyClass *c in products) { ... }
    – DrDev
    Commented Jun 19, 2013 at 13:15
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.