Skip to content

Instantly share code, notes, and snippets.

@mapedd
Last active August 29, 2015 14:15
Show Gist options
  • Save mapedd/bc51b9da4390789fec70 to your computer and use it in GitHub Desktop.
Save mapedd/bc51b9da4390789fec70 to your computer and use it in GitHub Desktop.
Find missing numbers in array of sorted consecutive natural numbers [n,n+1, n+2, ... n + m] Objective-C
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
NSArray *missingNumbers(NSArray *a){
if(a.count < 2){
return [NSArray new];
}
NSMutableArray *array = [NSMutableArray new];
for (NSInteger i = 0; i < a.count - 1; i ++) {
NSNumber *x = a[i];
NSNumber *y = a[i+1];
NSInteger xInt = [x integerValue];
NSInteger yInt = [y integerValue];
NSInteger diff = yInt - xInt;
if(diff > 1){
for (NSInteger i = xInt + 1; i < yInt; i++) {
[array addObject:@(i)];
}
}
}
return array;
}
int main(int argc, char *argv[]) {
@autoreleasepool {
NSArray *a = @[@1,@3,@5];
NSArray *r = missingNumbers(a);
NSArray *e = @[@2,@4];
NSCAssert([r isEqualToArray:e],@"");
a = @[@2,@5];
r = missingNumbers(a);
e = @[@3,@4];
NSCAssert([r isEqualToArray:e],@"");
a = @[@10,@20];
r = missingNumbers(a);
e = @[@11,@12,@13,@14,@15,@16,@17,@18,@19];
NSCAssert([r isEqualToArray:e],@"");
a = @[@99,@101,@102,@104];
r = missingNumbers(a);
e = @[@100,@103];
NSCAssert([r isEqualToArray:e],@"");
a = @[@9,@11,@13,@16];
r = missingNumbers(a);
e = @[@10,@12,@14,@15];
NSCAssert([r isEqualToArray:e],@"");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment