Compare two arrays - iphone

I have two arrays:
array1=[1,2,3,4,5,6,7,8,9,10,11]
array2=[1,2]
I want to compare weather elements in "array2" is present in "array1" or not.
If yes then I need to run a function, otherwise exit.
How to do it?

I have get the common items like this:-
NSMutableSet *idSet=[NSMutableSet setWithArray:Array1];
[idSet intersectSet:[NSSet setWithArray:Array2]];
NSArray *Common_array=[idSet allObjects];
in common array you can get the same object that are present in both array and is 0 object in
Common_array than in both array there is none on object that are same.

What about enumerating over array1?
Something along the lines of
NSArray *array1 = ...;
NSArray *array2 = ...;
[array1 enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([array2 containsObject: obj]) {
// Run the function you wanted to
}
}];

An easy logic way to do this would be a for loop:
for(int a = 0; a < array1.count; a++) {
for(int b = 0; b < array2.count; b++) {
if([[array1 objectAtIndex:a] isEqualToString:[array2 objectAtIndex:b]]) {
//do something here
}
}
}

Related

indexOfObject in an NSMutableArray returning garbage value

Trying to get index on an object in NSMutableArray. It is returning some garbage value, not getting why it is not returning index of particular item. Below is code i tried.
NSString *type = [dictRow valueForKey:#"type"];
if([arrSeatSel indexOfObject:type])
{
NSUInteger ind = [arrSeatSel indexOfObject:type];
[arrTotRows addObject:[arrSeatSel objectAtIndex:ind]];
}
type contains value "Gold". And arrSeatSel contains
(
"Gold:0",
"Silver:0",
"Bronze:1"
How to check that. Please guide.
The value you are getting is NSNotFound. You are getting NSNotFound because #"Gold" is not equal to #"Gold:0".
You should try the following
NSUInteger index = [arrSeatSel indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop){
return [obj hasPrefix:type];
}];
if (index != NSNotFound) {
[arrTotRows addObject:[arrSeatSel objectAtIndex:index]];
}
UPDATE
-indexOfObjectPassingTest: is a running the following loop. NOTE: /* TEST */ is some code that returns true when the correct index is found.
NSUInteger index = NSNotFound;
for (NSUInteger i = 0; i < [array count]; ++i) {
if (/* TEST */) {
index = i;
break;
}
}
In my first sample, /* TEST */ is [obj hasPrefix:type]. The final for loop would look like.
NSUInteger index = NSNotFound;
for (NSUInteger i = 0; i < [arrSeatSel count]; ++i) {
if ([arrSeatSel[i] hasPrefix:type]) {
index = i;
break;
}
}
if (index != NSNotFound) {
[arrTotRows addObject:[arrSeatSel objectAtIndex:index]];
}
I like -indexOfObjectPassingTest: better.
The [obj hasPrefix:type] part is just a different way to comparing strings. Read the -hasPrefix: doc for more details.
Hope that answers all your questions.
Sometimes storing data properly can solve lot of hazzle. If I guess correctly
"Gold:0" denotes a circle of type Gold an its count 0.
You can try to reformat that to an array of items.
Such as
[
{
"Type": "Gold",
"Count": 0
},
{
"Type": "Silver",
"Count": 0
},
{
"Type": "Bronze",
"Count": 1
}
]
And then using predicate to find the index
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"Type == %#",#"Gold"];
NSUInteger index = [types indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
[predicate evaluateWithObject:obj];
}];
You can try doing this.
[arrSeatSel enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) {
// object - will be your "type"
// idx - will be the index of your type.
}];
hope this helps.
If I'm reading that correctly, you're saying that arrSeatSel contains three NSStrings, #"Gold:0", #"Silver:0", and #"Bronze:1", correct?
And then your NSString* type is basically #"Gold"
The first thing is Gold and Gold:0 are different strings, and that's just for starter.
As you are searching for a string in the array, you should take each string out, and do a string matching, not just a comparison. What I'm saying is this:
NSString* str1 = #"This is a string";
NSString* str2 = #"This is a string";
if ( str1 == str 2 ) NSLog(#"Miracle does happen!")
The conditional would never be true even though both NSStrings contain the same value, they are different object, thus are different pointers pointing to different blocks of memory.
What you should do here is a string matching, I will recommend NSString's hasPrefix: method here, as it seems to fit your need.

How to store objects of a mutable Array into another mutable array in form of arrays.?

I have an NSMutable array which contains some objects and I want to store these objects into a different Mutable array in the form of different arrays.
For ex: I have an array named sessionArrayType4 which has these objects.
"New Attendee Reception",
"Attendee Reception",
"Banquett",
"Tour and BBQ"
And I want to store in another Mutable array named globalSessionArray and I'm expecting result something like below.
(("New Attendee Reception"), ("Attendee Reception"), (Banquett), (Tour and BBQ))
Here is my code:
if(self.pickerSelectedRow == [self.typePickerArray objectAtIndex:3])
{
for (int i =0; i< [self.sessionArrayType4 count]; i++)
{
if(self.displayTime == [[self.sessionArrayType4 objectAtIndex:i]valueForKey:#"start_time"])
{
[self.sessionRowArray addObject:[[self.sessionArrayType4 objectAtIndex:i]valueForKey:#"session_name"]];
self.rowCount = self.rowCount + 1;
}
else
{
[self.sessionRowArray removeAllObjects];
self.displayTime = [[self.sessionArrayType4 objectAtIndex:i] valueForKey:#"start_time"];
[self.sessionRowArray addObject:[[self.sessionArrayType4 objectAtIndex:i]valueForKey:#"session_name"]];
[self.globalSessionArray addObject:self.sessionRowArray];
}
}
}
But I am getting output something like this:
((Tour and BBQ), (Tour and BBQ), (Tour and BBQ), (Tour and BBQ))
You're going to have to alloc/init your values into an object for each iteration of the for loop or else it will continually stick in memory and overwrite itself.
if(self.pickerSelectedRow == [self.typePickerArray objectAtIndex:3])
{
NSArray *
for (int i =0; i< [self.sessionArrayType4 count]; i++)
{
NSObject *myNewObject = [[NSObject alloc] init];
if(self.displayTime == [[self.sessionArrayType4 objectAtIndex:i]valueForKey:#"start_time"])
{
myNewObject = [[self.sessionArrayType4 objectAtIndex:i]valueForKey:#"session_name"];
[self.sessionRowArray addObject: myNewObject];
self.rowCount = self.rowCount + 1;
}
else
{
[self.sessionRowArray removeAllObjects];
//NSLog(#"%#",self.sessionRowArray);
self.displayTime = [[self.sessionArrayType4 objectAtIndex:i] valueForKey:#"start_time"];
myNewObject = [[self.sessionArrayType4 objectAtIndex:i]valueForKey:#"session_name"]];
[self.sessionRowArray addObject:myNewObject];
// NSLog(#"%#",self.sessionRowArray);
[self.globalSessionArray addObject:self.sessionRowArray];
// NSLog(#"%#",self.globalSessionArray);
}
}
}
You need to allocate an temp array in for loop to get a final array of arrays.
The code is very confusing but you can modify like below to get correct result:
if(self.pickerSelectedRow == [self.typePickerArray objectAtIndex:3])
{
for (int i =0; i< [self.sessionArrayType4 count]; i++)
{
if(self.displayTime == [[self.sessionArrayType4 objectAtIndex:i]valueForKey:#"start_time"])
{
[self.sessionRowArray addObject:[[self.sessionArrayType4 objectAtIndex:i]valueForKey:#"session_name"]];
self.rowCount = self.rowCount + 1;
}
else
{
[self.sessionRowArray removeAllObjects];
NSMutableArray* tempArray = [[NSMutableArray alloc] init];
//NSLog(#"%#",self.sessionRowArray);
self.displayTime = [[self.sessionArrayType4 objectAtIndex:i] valueForKey:#"start_time"];
[tempArray addObject:[[self.sessionArrayType4 objectAtIndex:i]valueForKey:#"session_name"]];
// NSLog(#"%#",self.sessionRowArray);
[self.globalSessionArray addObject:tempArray];
// NSLog(#"%#",self.globalSessionArray);
}
1)
if(self.pickerSelectedRow == [self.typePickerArray objectAtIndex:3])
This expression and similar ones look like incorrect, because the left value look likes int or NSInteger and right value is NSObject. If they are both NSObjects then use isEqual instead.
2)
sessionArrayType4
it is correct, but no serious programmer uses such names for variables.
3)It is hard to understand what do you want because of incomplete code and a lot of NSLog calls. You have also added JSON code which is particularly incompatible with a previous part of code.
So edit your code first

Using a for-in loop with NSInteger?

I have an NSMutableArray populated with NSIntegers. I need to loop through the array. I could do:
// given NSMutableArray *array of NSIntegers
NSUInteger n = [array count];
for (NSInteger i = 0; i < n; i++) {
NSInteger x = [array objectAtIndex:i];
// query SQLite WHERE id = x
}
However, it seems that a for (object in array) loop would be cleaner. iOS 5 does not accept NSIntegers or NSNumbers as objects in for-in loops. Should I loop through the array with NSObjects, casting the NSObject to an NSInteger during each iteration? Is there another way? Or is a for loop like the one above the cleanest solution to this problem?
In Objective-C you can use a for-in loop with NSNumber like this:
NSArray *array = /*NSArray with NSNumber*/;
for (NSNumber *n in array) {
NSLog(#"i: %d", [n intValue]);
}
Check this out.
Mostly, you will not be allowed to have an NSMutableArray of NSUInteger (aka unsigned long) as it's not an objective-c object.
You may use the c style.
NSUInteger array[] = {value1,value2,value3};
int size = sizeof(array)/sizeof(array[0]);
for (int i=0; i<size; i++) {
NSInteger value = array[i];
// do whatever you want
}

Order, bucket sort, and order buckets of NSMutableArray

I have an NSArray of Object that has an interesting property that I would like to use in the following way: Given my array of objects with properties:
Object1 - Property A;
Object2 - Property A;
Object3 - Property B;
Object4 - Property D;
Object5 - Property D;
Object6 - Property D
I want these to be bucket sorted by their properties into a new array:
Array1 - Objects Object1, Object2
Array2 - Objects Object3
Array3 - Objects Object 4, Object5, Object6
And then within each array, sort by using a timeStamp property.
I have tried to accomplish this naively by creating a dictionary, adding interesting objects to the dictionary by property like if ([dictionary objectForKey:#"propertyVal"]) //add object else // create array for key, add object to array. This approach has not worked as expected because I end up needing to dekey the NSMutableDictionary using allKeysForValue, which is not reliable.
I feel that this is a fairly common problem and I would love to hear any insight into how I might go about solving this. Code is great, but even an algorithm (with the appropriate objects to use) should suffice.
It's not a proper bucket sort, but should work for a set of three properties. A bit of fiddling and you should be able to adjust it for any number of properties:
Edit. I made a dynamic version (just set property type to what you need):
- (NSMutableArray *)order:(NSDictionary *)objects byProperty:(id)property {
NSMutableSet *propertySet = [NSMutableSet setWithCapacity:5]; // so we can count the unique properties
for (Object *obj in [objects allValues]) {
[propertySet addObject:[obj property]];
}
NSMutableArray *objectCollections = [NSMutableArray arrayWithCapacity:[propertySet count]];
// create arrays for every property
for (int i = 0; i < [objects allValues]; i++) {
NSMutableArray *collection = [NSMutableArray arrayWithCapacity:5];
[objectCollections addObject:collection];
}
NSArray *allProperties = [propertySet allObjects];
// push objects into arrays according to a certain property
for (Object *obj in [dictionary allValues]) {
[[objectCollections objectAtIndex:[allProperties indexOfObject:[obj property]] addObject:obj];
}
NSMutableArray *result = [NSMutableArray arrayWithCapacity:[objectCollections count]];
// sort arrays by timestamp
for (int i = 0; i < [objectCollections count]; i++) {
[result addObject:[[objectCollections objectAtIndex:i] sortedArrayUsingComparator:^(id obj1, id obj2) {
if ([(Object *)obj1 timeStamp] > [(Object *)obj2 timeStamp]) {
return (NSComparisonResult)NSOrderedAscending;
}
if ([(Object *)obj1 timeStamp] < [(Object *)obj2 timeStamp]) {
return (NSComparisonResult)NSOrderedDescending;
}
return (NSComparisonResult)NSOrderedSame;
}];
}
return result;
}

Gather the count of a specific object from NSMutableArray

Hey guys & girls,
Im wondering how I can find the object count of a specific type of object in an array.
For example, i have 6 'clouds' in NSMutableArray at random locations, I also have 4 'dragons' in this NSMutableArray.
How can i gather the integer 6?
I was thinking something along the lines of:
int z = [[SomeClass *clouds in _somearray] count];
Any assistance would be greatly appreciated.
Thnx,
Oliver.
Yet another way is in using blocks:
Class cloadClass = NSClassFromString(#"Cloud");
NSArray *a = /* you array with clouds and dragons */;
NSIndexSet *clouds = [a indexesOfObjectsPassingTest:
^(id obj, NSUInteger idx, BOOL *stop) {
return [obj isKindOfClass:cloadClass];
}];
// now we can count clouds
NSLog(#"%d", [clouds count]);
// but also we now can return our clouds immediately and
NSLog(#"%#", [a objectsAtIndexes:clouds]);
int result = 0;
for (NSObject *object in _somearray) {
if ([object isKindOfClass:[SomeClass class]])
result++;
}
result is the count you are looking for
If you're looking for how many times a specific instance of an object appears, you can do:
NSCountedSet *counts = [NSCountedSet setWithArray:myArrayOfObjects];
NSUInteger count = [counts countForObject:myObject];
Otherwise you'd just have to loop through the array manually and count.