I have two arrays.
At first, I was comparing the counts of both of the arrays
than putting them in an NSSet
to check if they contained keywords. If that bool
returned true, then I added them to finalArray
.
NSInteger int1 = inputArray.count;
NSInteger int2 = databaseArray.count;
if (int1 == int2) {
NSArray *array = [inputArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"ANY %@ contains[cd] self", databaseArray]];
NSSet *set1 = [NSSet inputArray];
NSSet *set2 = [NSSet setWithArray:array];
if([set1 isEqualtoSet:set2]) {
Consider the following case:
inputArray = @"John", @"Kyle"
dataBaseArray[0] = @"third john Stewart", @"second kyle braflowski"
In this example, my code would add the item to my finalArray
because inputArray.count == dataBasesArray.count
(i.e. 2 == 2) and set 2 contains "john" and "kyle."
But it turns out my algorithm is wrong for my purposes.
Consider the following example (written in pseudocode):
inputArray = @"John" , @"Kyle", @"George", @"Mary"
dataBaseArray[0] = @"third john Stewart", @"second kyle braflowski"
databaseArray[3] = @"First Mary Steps", @"fourth kyle lomorik",@"second George steps"
I need my algorithm to add both of these items from the databaseArray
to the finalArray
since I have all the keys from inputArray
in both databaseArray[0]
(john,Kyle) and databaseArray[3]
(george,kyle,mary).
How can I get the proper solution in the case where inputArray.count > databaseArray.count?
a new example
input array = (@"rice", @"chicken",@"tomato",@"egg")
and lets say i got 2 item from my database that one has
(@"100 gr rice",@"250 gr chicken")
and the other (@"250 gr chicken",@"4 eggs",@"3 tomato@")
with this current input. i need to able to add both of the items from my database to a finalArray to show it on a tableView.
Your question isn't clear, but I am assuming that each element in your databaseArray
is an array of NSStrings.
The following method pulls each line in each element in databaseArray
apart into separate words and verifies that at least one word from each line in the supplies list.
- (NSArray *) intersectCandidates:(NSArray *)candidates withSupplies:(NSArray *)supplies
{
NSMutableArray *output=[[NSMutableArray alloc]init];
NSSet *suppliesSet=[NSSet setWithArray:supplies];
for (NSArray *candidateLines in candidates) {
int count=0;
for (NSString *candidateLine in candidateLines) {
NSArray *wordArray=[candidateLine componentsSeparatedByString:@" "];
for (NSString *word in wordArray) {
if ([suppliesSet contains:word]) {
++count;
break;
}
}
}
if (count == [candidateLines count]) { // We matched one word from each line
[output addObject:candidateLines];
}
}
return [NSArray arrayWithArray:output]; // Return a non-mutable copy
}
Because of the aforementioned XY problem, I am not sure that this is the most efficient way of solving your actual problem.