Compare two arrays and put equal objects into a new array [duplicate] - objective-c

This question already has answers here:
Finding Intersection of NSMutableArrays
(5 answers)
Closed 8 years ago.
How can I compare two NSArrays and put equal objects into a new array?

NSArray *array1 = [[NSArray alloc] initWithObjects:#"a",#"b",#"c",nil];
NSArray *array2 = [[NSArray alloc] initWithObjects:#"a",#"d",#"c",nil];
NSMutableArray *ary_result = [[NSMutableArray alloc] init];
for(int i = 0;i<[array1 count];i++)
{
for(int j= 0;j<[array2 count];j++)
{
if([[array1 objectAtIndex:i] isEqualToString:[array2 objectAtIndex:j]])
{
[ary_result addObject:[array1 objectAtIndex:i]];
break;
}
}
}
NSLog(#"%#",ary_result);//it will print a,c

Answer:
NSArray *firstArr, *secondArr;
// init arrays here
NSMutableArray *intersection = [NSMutableArray array];
for (id firstEl in firstArr)
{
for (id secondEl in secondArr)
{
if (firstEl == secondEl) [intersection addObject:secondEl];
}
}
// intersection contains equal objects
Objects will be compared using method compare:. If you want to use another method, then just replace if (firstEl == secondEl) with yourComparator that will return YES to equal objects: if ([firstEl yourComparator:secondEl])

//i assume u have first and second array with objects
//NSMutableArray *first = [ [ NSMutableArray alloc]init];
//NSMutableArray *second = [ [ NSMutableArray alloc]init];
NSMutableArray *third = [ [ NSMutableArray alloc]init];
for (id obj in first) {
if ([second containsObject:obj] ) {
[third addObject:obj];
}
}
NSLog(#"third is : %# \n\n",third);
more over if u have strings in both array then look at this answer of mine
Finding Intersection of NSMutableArrays

Related

Adding objects to an NSmutableArray from a C Array

I have an NSmutable array and I am adding some strings present in the C array to it. By using this method
if (!self.arrayOfVariableNames) {
self.arrayOfVariableNames = [[NSMutableArray alloc] init];
for (int i = 0; i< cols; i++) {
[self.arrayOfVariableNames addObject:[NSString stringWithCString:cArrayOfVariableNames[i] encoding:NSUTF8StringEncoding ]];
}
}
else{
[self.arrayOfVariableNames removeAllObjects];
for (int i = 0; i< cols; i++) {
[self.arrayOfVariableNames addObject:[NSString stringWithCString:cArrayOfVariableNames[i] encoding:NSUTF8StringEncoding ]];
}
}
Does this method ensure that the objects in the NSmutableArray won't be deallocated when the C array is taken out of memory?
if this array arrayOfVariableNames is becoming Null, then the problem is with the initialisation of the array. Please try to use Lazy loading by doing this:
- (NSArray*)arrayOfVariableNames {
if (!_arrayOfVariableNames) {
_arrayOfVariableNames = [[NSMutableArray alloc] init]; //initialise the array if needed
}
return _arrayOfVariableNames; //else return the already initialized array
}
and please comment out this line in your code: self.arrayOfVariableNames = [[NSMutableArray alloc] init];
****EDIT****
Please find the update code in https://docs.google.com/file/d/0BybTW7Dwp2_vdHhQN1p1UzExdTA/edit?pli=1. Have a look at it.
Yes. NSArray retains anything in it.
But you should stop chaining your NSString creation and instead creat a string a line before adding it to the array. Then check for nil.
Only add it to the array if it is not nil.
Do code defensively.
arrayOfVariableNames will not change when the C array get deallocated.
Make sure that your arrayOfVariableNames variable is strong.
#property (nonatomic, strong) NSMutableArray *arrayOfVariableNames;
if (!self.arrayOfVariableNames)
{
self.arrayOfVariableNames = [[NSMutableArray alloc] init];
}
else
{
[self.arrayOfVariableNames removeAllObjects];
}
for (int i = 0; i< cols; i++)
{
NSString *tempString = [NSString stringWithCString:cArrayOfVariableNames[i] encoding:NSUTF8StringEncoding];
if([tempString length] > 0)
{
[self.arrayOfVariableNames addObject:tempString];
}
else
{
NSLog(#"string is empty");
}
}

how to compare 2 NSMutableArray and get different number of value

I want compare 2 NSMutableArray values and check which indexPath is different and store this numbers of index in one array.
for example I have these NSMutableArray :
NSMutableArray *a = [[NSMutableArray alloc]initWithObjects:#"1",#"2",#"3",#"4",#"5",#"6", nil];
NSMutableArray *b = [[NSMutableArray alloc]initWithObjects:#"11",#"2",#"5",#"3",#"53",#"6", nil];
and I want to compare these two NSMutableArray index to index (compare value to value) and tell me that which index of array in these NSMutableArrays is different. for example in two NSMutableArray on top this index is different (0,2,3,4) and I want store this values in certain Array.
NSMutableArray* differentIndex;
differentIndex = [[NSMutableArray alloc] init];
for(int i = 0 ; i < [a count]; i++) {
if(i < [b count]){
if(![b[i] isEqual:a[i]]){
[differentIndex addObject:[NSNumber numberWithInt:i]];
}
} else {
[differentIndex addObject:[NSNumber numberWithInt:i]];
}
}
Now your differentIndex contains all the different index in the arrays. :)
NSMutableArray *a = [[NSMutableArray alloc]initWithObjects:#"1",#"2",#"3",#"4",#"5",#"6", nil];
NSMutableArray *b = [[NSMutableArray alloc]initWithObjects:#"11",#"2",#"5",#"3",#"53",#"6", nil];
NSMutableArray *new = [[NSMutableArray alloc]init];
for(int i =0;i<[b count]<=[a count]?[b count]:[a count];i++)
{
NSString *_keyA = [a objectAtIndex:i];
NSString *_keyB = [b objectAtIndex:i];
if ([_keyA isEqualToString:_keyB])
continue;
[new addObject:[NSString stringWithFormat:#"%d",i]];
}

Selecting array elements using a binary pattern as the selector

I have an NSArray, and I've calculated a list of integers that represent (in binary) the elements I need to pull out of the array into a new array.
For example, I have 7, 11, and 13, whose bit patterns are 000111, 001011, and 001101. I want to grab three arrays, made of elements 0,1,2, then elements 0,1,3, and then 0,2,3 out of the main array.
Construct an NSIndexSet from the bit patterns you have:
#implementation NSIndexSet (NonContiguous)
+ (instancetype)indexSetFromMask:(NSUInteger)mask
{
NSMutableIndexSet * set = [NSMutableIndexSet indexSet];
for( NSUInteger i = 0; i < (sizeof(NSUInteger) * 8); i++ ){
if( mask & (1l << i) ){
[set addIndex:i];
}
}
return set;
}
#end
Then use objectsAtIndexes:
[origArray objectsAtIndexes:[NSIndexSet indexSetFromMask:7]];
// etc.
Assuming you want the output to be in the form [[a,b,c],[a,b,d],[a,c,d]] for the example, you could do something like this:
NSArray *sourceArray = [[NSArray alloc] initWithObjects:#"a",#"b",#"c",#"d",...,nil];
NSArray *grabArray = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:7],[NSNumber numberWithInt:11],[NSNumber numberWithInt:13],...,nil];
NSMutableArray *resultArray = [[NSMutableArray alloc] init];
Then for each element of grabArray, add the correct elements to resultArray:
for (NSNumber num in grabArray) {
int n = [num intValue];
int bit = floor(log2(n)); //get highest bit in the current number
NSMutableArray *curr = [[NSMutableArray alloc] init];
while (n>0) {
if (n>pow(bit,2)) { //if this bit is a 1
[curr addObject:[sourceArray objectAtIndex:bit]];
}
n-=pow(bit,2);
bit-=1;
}
[resultArray addObject:curr];
}
Then resultArray should be the array you are looking for. It will add the objects in reverse order, so if order matters you would want to use [curr insertObject: [sourceArray objectAtIndex:bit] atIndex:0]; instead.

Get matched string from two NSArrays

How can I save the string that match from one NSArray with one index difference in NSMutableArray?
For example, there are three "apple", four "pineapple", six "banana", two "cocoa" and the rest of words dont have duplicate(s) in the nsarray, i would like to know if the nsarray has at least two same words. If yes, I would like to save "apple", "pineapple, "banana" and "cocoa" once in nsmutablearray. If there are other alike words, I would like to add them to namutablearray too.
My code (which still doesn't work properly);
NSArray *noWords = [[NSArray alloc] initWithArray:
[[NSString stringWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:#"words" ofType:#"txt"]
encoding:NSUTF8StringEncoding error:NULL]
componentsSeparatedByString:#"\n"]];
NSUInteger scount = [noWords count];
int ii = 0;
NSString *stringline;
for (ii; ii < scount; ii++)
{
stringline = [noWords objectAtIndex:ii];
NSLog(#"stringline : %# ", stringline);
}
int i = 1;
NSString *line;
for (i ; i < 10; i++)
{
line = [noWords objectAtIndex:i];
NSLog (#"line : %# ", line);
NSMutableArray *douwords = [NSMutableArray array];
if ([stringline isEqualToString:line])
{
NSString *newword;
for (newword in douwords)
{
[douwords addObject:newword];
NSLog (#"detected! %# ", douwords);
}
}
}
Here's a solution using two sets:
- (NSArray *)getDuplicates:(NSArray *)words
{
NSMutableSet *dups = [NSMutableSet set],
*seen = [NSMutableSet set];
for (NSString *word in words) {
if ([seen containsObject:word]) {
[dups addObject:word];
}
[seen addObject:word];
}
return [dups allObjects];
}
Assuming NSSet uses hash tables behind the scenes (which I'm betting it does), this is going to be faster than the previously suggested O(n^2) solution.
Here's something off the top of my head:
NSMutableSet* duplicates = [NSMutableSet set];
NSArray* words = [NSArray arrayWithObjects:#"Apple", #"Apple", #"Orange", #"Apple", #"Orange", #"Pear", nil];
[words enumerateObjectsUsingBlock:^(NSString* str, NSUInteger idx, BOOL *stop) {
for (int i = idx + 1; i < words.count; i++) {
if ([str isEqualToString:[words objectAtIndex:i]]) {
[duplicates addObject:str];
break;
}
}
}];
NSLog(#"Dups: %#", [duplicates allObjects]); // Prints "Apple" and "Orange"
The use of an NSSet, as opposed to an NSArray, ensures strings are not added more than once. Obviously, there are optimizations that could be done, but it should be a good starting point.
I assume that you want to count appearances of words in your array and output those with a count of more than one. A basic and verbose way to do that would be:
// Make an array of words - some duplicates
NSArray *wordList = [[NSArray alloc] initWithObjects:
#"Apple", #"Banana", #"Pencil",
#"Steve Jobs", #"Kandahar",
#"Apple", #"Banana", #"Apple",
#"Pear", #"Pear", nil];
// Make an mutable dictionary - the key will be a word from the list
// and the value will be a number representing the number of times the
// word appears in the original array. It starts off empty.
NSMutableDictionary *wordCount = [[NSMutableDictionary alloc] init];
// In turn, take each word in the word list...
for (NSString *s in wordList) {
int count = 1;
// If the word is already in the dictionary
if([wordCount objectForKey:s]) {
// Increse the count by one
count = [[wordCount objectForKey:s] intValue] + 1;
}
// Save the word count in the dictionary
[wordCount setObject:[NSNumber numberWithInt:count] forKey:s];
}
// For each word...
for (NSString *s in [wordCount keysOfEntriesPassingTest:
^(id key, id obj, BOOL *stop) {
if ([obj intValue] > 1) return YES; else return NO;
}]) {
// print the word and the final count
NSLog(#"%2d %#", [[wordCount objectForKey:s] intValue], s);
}
The output would be:
3 Apple
2 Pear
2 Banana

Different Keys Point to Same Object(s) in NSMutableDictionary

I have a custom object called Person that among other things contains an NSString field called descriptor, which stores what sort of person that Person object is (angry, sad, wild, happy, morose, etc). All of my Person objects are in an NSMutableArray, but I would like to store them in an NSMutableDictionary in such a manner:
Key: A, Object: An NSMutableArray where all Person objects have descriptor starting with 'A'
Key: B, Object: An NSMutableArray where all Person objects have descriptor starting with 'B'
Key: C, Object: An NSMutableArray where all Person objects have descriptor starting with 'C'
etc...
I've tried to do this in my code below, and at the comment //POINT 1, the keys and arrays seem to match up, but at //POINT 2, when I print out the complete dictionary, all the keys come up with the same values!
So I wanted to know why the NSMutableArray I seem to have is not being stored as I want it in the NSMutableDictionary?
- (void)buildDictionaryForIndexList {
NSMutableDictionary *tempDict = [[[NSMutableDictionary alloc] init] autorelease];
NSMutableArray *personsStartingWithLetter = [[NSMutableArray alloc] init];
NSMutableArray *indexList = [[[NSMutableArray alloc] init] autorelease];
NSInteger loopCounter = 1;
NSString *firstLetter = [[[NSString alloc] init] autorelease];
for (Person *v in persons) {
firstLetter = [[v descriptor] substringWithRange:NSMakeRange(0, 1)];
if ([indexList containsObject:firstLetter]) {
[personsStartingWithLetter addObject:v];
if (loopCounter == [persons count]) {
[tempDict setObject:personsStartingWithLetter forKey:firstLetter];
}
} else {
if (loopCounter > 1) {
//POINT 1
NSLog(#"%#",[indexList objectAtIndex:[indexList count]-1]);
for (Person *q in personsStartingWithLetter) {
NSLog(#"%#",[q descriptor]);
}
[tempDict setObject:personsStartingWithLetter forKey:[indexList objectAtIndex:([indexList count] - 1)]];
[personsStartingWithLetter removeAllObjects];
}
[indexList addObject:firstLetter];
[personsStartingWithLetter addObject:v];
} // else
loopCounter++;
} // for
//POINT 2
NSEnumerator *enumerator = [tempDict keyEnumerator];
for (NSString *str in enumerator) {
NSLog(#"%#",str);
for (Person *c in [tempDict objectForKey:str]) {
NSLog(#"%#",[c descriptor]);
}
}
self.dictionary = tempDict;
} // buildDictionaryForIndexList
So, for example, at POINT 1 my output is:
A
Angry
Amiable
B
Belligerent
C
Cool
...
W
Wild
but at POINT 2 my output is
T
Wild
J
Wild
A
Wild
...
W
Wild
Change [tempDict setObject:personsStartingWithLetter forKey:[indexList objectAtIndex:([indexList count] - 1)]]; (just after point 1) to [tempDict setObject:[[personsStartingWithLetter copy] autorelease] forKey:[indexList objectAtIndex:([indexList count] - 1)]];. The problem is that NSDictionary copies the key, but retains the value. Therefore, if you add a mutable array to the dictionary and then change it, the array in the dictionary also changes. You need to create a non-mutable copy of the array to put in the dictionary.
The whole method is a bit overcomplicated.
- (void)buildDictionaryForIndexList
{
NSMutableDictionary *tempDict = [[[NSMutableDictionary alloc] init] autorelease];
for (Person *v in persons)
{
NSString* firstLetter = [[v descriptor] substringWithRange:NSMakeRange(0, 1)];
NSMutableArray* personsStartingWithLetter = tempDict [firstLetter];
if (personsStartingWithLetter == nil)
{
personsStartingWithLetter = [NSMutableArray array];
tempDict [firstLetter] = personsStartingWithLetter;
}
[personsStartingWithLetter addObject:v];
} // for
self.dictionary = tempDict;
}
You start with an empty dictionary that will contain arrays. For every person, you check whether there is a suitable array or not, and if there isn't one, you create it. So now there is an array for the person, so you add it to the array. That's all.