Created
October 3, 2016 01:46
-
-
Save ajayjapan/6183be49617a0a19a1d6f65e361a1c80 to your computer and use it in GitHub Desktop.
Two functions on how to handle zero elements in an NSArray
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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