0

Here is what i need it to do.

NSArray has 10 objects

NSArray2 has the same 10 objects but in different indexes.

I need to compare if NSArray1 index:5 matches NSArray2 index:5 if not tell me if the object has moved up or down in the NSArray2, same for every other object inside that array.

The objects have the following properties: id and name.

Any suggestion on how i can accomplish this?

rmaddy
  • 314,917
  • 42
  • 532
  • 579

1 Answers1

1

If you have RAM to spare you could build a map from the object's id to its index in array 1, then scan array 2 and compare, like:

NSMutableDictionary *map = [[NSMutableDictionary alloc] init];
for (NSUInteger j = 0; j < array1.count; j++) {
    id object = array1[j];
    map[object.id] = @(j);
}
for (NSUInteger j = 0; j < array2.count; j++) {
    id object = array2[j];
    id identifier = object.id;
    NSUInteger array1Index = [map[identifier] unsignedIntegerValue];
    // Compare array1Index to j here.
}

That'll let you compare with a running time that grows like the number of objects in the arrays, but note that you have to spend some extra RAM to make that map. You could compare with only constant RAM costs if you're willing to spend more time:

for (NSUInteger j = 0; j < array1.count; j++) {
    id object = array1[j];
    NSUInteger k = [array2 indexOfObject:object];
    // Compare j and k, note that k could be NSNotFound.
}

And that should have a running time that grows like the product of the array counts.

Aaron Golden
  • 7,092
  • 1
  • 25
  • 31