I am working through challenges at CodeEval.com and wanted to get your input on my code for this challenge.
Given a list of numbers and a positive integer k, reverse the elements of the list, k items at a time. If the number of elements is not a multiple of k, then the remaining items in the end should be left as is.
Input sample:
Your program should accept as its first argument a path to a filename. Each line in this file contains a list of numbers and the number k, separated by a semicolon. The list of numbers are comma delimited.
E.g. input:
1,2,3,4,5;2 1,2,3,4,5;3
Output sample:
Print out the new comma separated list of numbers obtained after reversing. E.g.
2,1,4,3,5 3,2,1,4,5
-(void)reversedGroups
{
NSString *line = @"22,23,24,25,26,27,28,29,30;3"; //input sample
NSArray *lineArray = [line componentsSeparatedByString:@";"];
NSUInteger numbElements = [[lineArray lastObject] intValue];
NSArray *elementsArray = [[lineArray objectAtIndex:0] componentsSeparatedByString:@","];
NSMutableArray *resultLineArray = [[NSMutableArray alloc]init];
NSUInteger pos = 0;
while (pos<[elementsArray count]) {
//itterating through the elements
if (pos+numbElements <= [elementsArray count]) {
//make sure that i have enough elements to reverse
for (NSUInteger i = pos+numbElements; i>pos; i--) {
//add elements in reverse to the result array
[resultLineArray addObject:[elementsArray objectAtIndex:i-1]];
}
}else {
for (NSUInteger j = pos; j<[elementsArray count]; j++) {
//add elements that are left to the result array
[resultLineArray addObject:[elementsArray objectAtIndex:j]];
}
}
pos += numbElements; // move the postion by number of elements to reverse
}
//convert results array to string and add comma after each element as required for output
NSString *resultString = [[resultLineArray valueForKey:@"description"] componentsJoinedByString:@","];
NSLog(@"%@",resultString);
}