Reputation: 7
I have an array in Objective-C that stores basic mileage data. So each time I add to the array I add 4 elements (miles, litres, cost, MPG). If I save 10 entries I'll end up with 10 elements for say cost. How do I iterate through a specific element, assign them an index, add (total) them all up then divide by the total index number?? I've found plenty of info looping through basic arrays that just contain numbers and performing an average but I can't seem to get it to narrow down to a specific element? Should I create a new array with just the data that I need, then average that data, or can I work directly on the main array, which would be easier?
This will just work for a flat array if it were populated with just my cost data, it'll loop through and print to the console
for (NSString* string in arrayOfStrings ){
NSLog(@"%@", string);
}
So how would I drill down into this array say and achieve the same thing looking for my specific element of cost. I think I could work my way from there?
arrayOfStrings.cost
Upvotes: 0
Views: 159
Reputation: 5665
If you create a class that has a cost property:
@interface MYCostObject : NSObject
@property double cost;
@end
You might think you can just loop over a collection of MYCostObjects:
MYCostObject* foo = [[MYCostObject alloc] init];
MYCostObject* bar = [foo copy];
foo.cost = 10.0;
bar.cost = 2.0;
NSArray* myArray = @[foo, bar];
double sum = 0.0;
for (MYCostObject* costObj in myArray)
{
sum += costObj.cost;
}
double avg = sum/myArray.count;
But you could also just skip the enumeration in a loop and use a collection operator:
NSNumber* avg = [myArray valueForKeyPath:@"@avg.cost"];
Upvotes: 1
Reputation: 9522
you should post some code as I am unclear what you made an array of. Elements in an array just have an index, not a name. You might want an array of NSDictionaries. Then do something like:
int sum = 0;
int count = 0;
for(NSDictionary *entry in myArray) {
NSNumber cost = [entry valueForKey:@"cost"];
if(cost) {
sum += [cost intValue];
count++;
}
}
int costAvg = sum / count;
Upvotes: 0