node ninja
node ninja

Reputation: 33056

How to sort this NSMutableArray?

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?

Upvotes: 1

Views: 570

Answers (2)

kubi
kubi

Reputation: 49414

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!

Upvotes: 1

davidstites
davidstites

Reputation: 687

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.

Upvotes: 1

Related Questions