I have an array containing twenty items. I want to search through the array, comparing one item to the next one in the array, and then print the larger item. I have already sorted the array. I just want to compare the two items, check what the remainder is between the two values, and if it's greater than say, four, print the larger item.
Asked
Active
Viewed 501 times
0
-
1Between every pair of values, or the values at two specific indexes, or what? Are your values `NSNumber`s? – jscs May 15 '13 at 19:37
-
1Iterate. There are several different ways to do it, but a plain old `for` loop should do fine. – Hot Licks May 15 '13 at 19:40
-
Some good practices for comparison [here](http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it?rq=1) – Pavel Oganesyan May 15 '13 at 19:41
-
It is an array of Objects, which has a name which is NSString and points which is an int. I want to compare the integers. – Daniel Buckle May 15 '13 at 20:06
2 Answers
0
NSArray* arr = [NSArray arrayWithObjects:
[NSNumber numberWithInt:1],
[NSNumber numberWithInt:6],
[NSNumber numberWithInt:7],
[NSNumber numberWithInt:11],
nil
];
int len = [arr count];
for (int i=0; i < len-1; ++i) {
int num1 = [[arr objectAtIndex:i] intValue];
int num2 = [[arr objectAtIndex:i+1] intValue];
if ( num2-num1 > 4 ) {
NSLog(@"%d", num2);
}
}
--output:--
6

7stud
- 46,922
- 14
- 101
- 127
-
1num2 will be num1 in the next iteration. Simply set num1 one time before entering the for loop, which should run from 1 -
– Amin Negm-Awad May 15 '13 at 20:27
0
NSEnumerator *itemEnumerator = [theArray objectEnumerator];
YourClass *lastObject = [itemEnumerator nextObject];
YourClass *compareObject;
while( (compareObject = [itemEnumerator nextObject]) != nil)
{
if( /* place your condition here */ )
{
NSLog( … );
}
lastObject = compareObject;
}
Typped in Safari

Amin Negm-Awad
- 16,582
- 3
- 35
- 50