Skip to content

Instantly share code, notes, and snippets.

@ajayjapan
Created October 3, 2016 01:46
Show Gist options
  • Save ajayjapan/6183be49617a0a19a1d6f65e361a1c80 to your computer and use it in GitHub Desktop.
Save ajayjapan/6183be49617a0a19a1d6f65e361a1c80 to your computer and use it in GitHub Desktop.
Two functions on how to handle zero elements in an NSArray
#import <Foundation/Foundation.h>
#import <stdio.h>
@interface MyClass : NSObject
@end
@implementation MyClass
// 1. returns the number of non-zero elements (4)
+ (int)numberOfZeroElementsInArray:(NSArray *)array {
int count = 0;
for (NSNumber *number in array) {
if ([number intValue] == 0) {
count ++;
}
}
return count;
}
// 2. moves the non-zero elements to the beginning of the array (the rest of the elements don't matter)
+ (NSArray *)nonZeroElementsToBeginningForArray:(NSArray *)array {
NSMutableArray *mutableArray = [array mutableCopy];
int point = 0;
int count = mutableArray.count;
NSMutableIndexSet *indexes = [NSMutableIndexSet new];
while (point < count) {
NSNumber *number = [mutableArray objectAtIndex:point];
if ([number intValue] == 0) {
[indexes addIndex:point];
[mutableArray addObject:number];
}
point ++;
}
[mutableArray removeObjectsAtIndexes:indexes];
return [mutableArray copy];
}
@end
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSArray *array = @[ @1, @0, @2, @0, @0, @3, @4 ];
printf("%i", [MyClass numberOfZeroElementsInArray:array]);
printf("\n");
printf("%s", [[[MyClass nonZeroElementsToBeginningForArray:array] componentsJoinedByString:@","] UTF8String]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment