views:

64

answers:

2

I made a class called Person. It looks like this

Person
-------
Name
Points

Then I created an NSMutableArray called team. It contains several of these person objects. I create several teams.

Then I created another NSMutableArray called allTeams. It holds all the team arrays.

I want to sort the allTeams array by the total number of points for each team, found by summing the points for each person in the team.

How can I do this?

+1  A: 

Why not maintain an int variable in the team object that is the cumulative score of each person on the team? When you wanted to do the comparison, simply sort based on that field. Any sort algorithm will work, with the obvious caveats of memory requirements (in place vs. extra allocated memory) and worst case running time (O(n^2), O(nlog(n)).

The calculation of the scores for all teams would be O(n^2) the first time the sort information is requested. After that, each time a person scores a point, simply call a selector that updates that persons score and then update the team score.

davidstites
The Team object would be an NSMutableArray, correct? Then would I have to subclass NSMutableArray in order to create this int variable?
awakeFromNib
Based on how you described the problem, the Person object would have an int ivar that held the score for that particular person. Depending on your needs, your Team object could be as simple as an NSMutableArray, or as complex as another object, depending on your needs. In either event it's an NSMutableArray, as you said; the only difference is whether it is "stand-alone" or that array of Persons is in a Team object. Similar logic would apply to the Teams NSMutableArray.
davidstites
+1  A: 

No need to muck around with extraneous ivars, unless you have millions of players and hundreds of thousands of teams, the naive implementation will be faster than you could possibly need.

@interface Team : NSObject {
    NSMutableArray *people;
}

@property (readonly) NSInteger score;

@end

@implimentation Team

- (NSInteger)score {

    NSInteger score = 0;

    for(Person *person in people) {
        score = score + person.points;
    }

    return score;
}

@end

// To sort an array of teams, do the following
// assumes that `teams` is a mutable array containing all teams

NSSortDescriptor *scoreSort = [[NSSortDescriptor alloc] initWithKey:@"score" ascending:NO];
[teams sortUsingDescriptors:[NSArray arrayWithObject:scoreSort]];
[scoreSort release];

Disclaimer: I wrote the above code without access to my Mac, so it may not compile as written, but it's close. Good luck!

kubi
Shouldn't Team be an NSMutableArray instead of an NSObject?
awakeFromNib
@awakeFromNib: No. Conceptually, a team is not just a collection of players, it has attributes that apply to it such as its name etc. It's much better to create a Team class that has, as one of its ivars a collection of players (exactly as kubi has done).
JeremyP