Skip to content

Instantly share code, notes, and snippets.

@icodebuster
Created December 31, 2015 07:19
Show Gist options
  • Save icodebuster/d5e73c4727efbd952a1b to your computer and use it in GitHub Desktop.
Save icodebuster/d5e73c4727efbd952a1b to your computer and use it in GitHub Desktop.
Random Array of numbers passed and get consecutive number range
NSMutableArray *randomNumbersArray;
randomNumbersArray = [NSMutableArray arrayWithObjects:@(1),@(2),@(4),@(6),@(9),@(11),@(12),@(14),@(15),@(21),@(22),@(23),@(24),@(25),@(27),@(28),@(30),@(31),@(33),@(35),@(36), @(41), @(40), nil];
- (NSArray *)getConsecutiveArray:(NSArray *)originalArray {
NSInteger startNumber, endNumber;
NSMutableArray *finalArray = [NSMutableArray array];
for (int index = 0; index < originalArray.count; index++) {
startNumber = [originalArray[index] integerValue];
endNumber = startNumber;
if (index != originalArray.count - 1) {
while ([originalArray[index] integerValue] - [originalArray[index + 1] integerValue] == -1) {
endNumber = [originalArray[index + 1] integerValue];
index++;
}
if (startNumber == endNumber) {
[finalArray addObject:[NSString stringWithFormat:@"%ld", startNumber]];
}
else {
[finalArray addObject:[NSString stringWithFormat:@"%ld-%ld", startNumber, endNumber]];
}
}
}
return finalArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment