Look for a cleaner way of doing this search function

Considering that there are 2 classes A and B.

They both receive an integer attribute, ID.

Now you have arrayA

one which contains all classes A and arrayB

which contains all objects of class B.

What is the best or cleaner way to select objects in arrayB

that has the same ID as the object in arrayA

?

(Someone suggests intersection. I think this is faster, but the code doesn't look very good)

Here's some sample code:

NSMutableArray *resultArray = [NSMutableArray array];

for (ClassB *bObject in arrayB) {  
    for (ClassA *aObject in arrayA) {  
        if ([bObject ID] == [aObject ID]) {  
            [resultArray addObject:bObject];  
            break;
        }
    }
}

      

+3


source to share


2 answers


The easiest way is to (a) build an array of ID values; and then (b) use a predicate:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ID IN %@", [arrayA valueForKey:@"ID"]];
NSArray *results = [arrayB filteredArrayUsingPredicate:predicate];

      



See the Predicate Programming Guide .

0


source


Your current solution has complexity O(nm)

, where n

and m

are lengths A

and B

respectively.

You can sort the array A

by ID in O(n log n)

, and then for each element B

, binary search which ID is in A

. It will be O(n log n + m log n)

. n log n

because of the sorting and m log n

because for each of the m

elements, B

you are doing one binary search on A

, which is done in logarithmic time.



You can also add each item in A

(just its id) to a hash table (you can name a map or a dictionary in your language of choice. I'm not familiar with objective-c.) And then for each item, B

find your id in the built hash table ... It will O(n + m)

, but in some cases it can degrade to the worst difficulty. In practice, this will probably be the fastest.

+2


source







All Articles