Reputation: 239
i would like to have the average of my NSArray element and store them in a new array in the following way.
NSArray* number;
NSMutableArray* Average;
[Average objectAtIndex:0]=[number objectAtIndex:0];
[Average objectAtIndex:1]=([number objectAtIndex:0] + [number objectAtIndex:1])/2;
[Average objectAtIndex:2]=([number objectAtIndex:0] + [number objectAtIndex:1] + [number objectAtIndex:2])/3;
i was thinking of doing it using 2 for loops
for (int i =0; i<[number count]; i++){
for (int j=0; j<i; j++){
temp+=[number objectAtIndex:j];
}
[Average addObject: temp/(i+1)];
}
can anyone help me with a more efficient way
thank you
Upvotes: 1
Views: 4315
Reputation: 437917
You only need one loop:
NSArray *numbers = @[@(2.4), @(2.7), @(4.0)];
NSMutableArray *averages = [NSMutableArray array];
double total = 0.0;
for (int i = 0; i < [numbers count]; i++) {
total += [[numbers objectAtIndex:i] doubleValue];
[averages addObject:@(total / (i + 1))];
}
or, using fast enumeration:
__block double total = 0.0;
[numbers enumerateObjectsUsingBlock:^(NSNumber *number, NSUInteger idx, BOOL *stop) {
total += [number doubleValue];
[averages addObject:@(total / (idx + 1))];
}];
By the way, unrelated to your question, but if you simply wanted to average all the numbers in the numbers
array, you could use KVC collection operator:
NSNumber *average = [numbers valueForKeyPath:@"@avg.self"];
Clearly that's only useful if you wanted to average all the numbers in the array, but it's a convenient shorthand in those situations.
Upvotes: 6