Question

I wonder if anyone could supply me with some efficient sample code please to pick up the top 3 elements in an array?

My array will simply contain a list of dates and what I want to do is pick the top 3 dates that are contained within.

I've seen a few example of returning common elements but nothing quite that will give me a top 3 list.

So if this were the contents of my array:

01/01/2013, 01/01/2013, 01/01/2013, 01/02/2013, 01/02/2013, 01/02/2013, 01/03/2013, 01/03/2013, 22/05/2013, 23/05/2013, 27/05/2013, 01/06/2013, 07/07/2013, 12/08/2013

then I would expect the top 3 dates to come out as:

01/01/2013, 01/02/2013, 01/03/2013

Any help would be most appreciated.

Was it helpful?

Solution

It took 30 minutes to find a solution to find the max 3 values...

Have a try:

NSArray *yourArray=@[@"01/01/2013", @"01/01/2013", @"01/01/2013", @"21/02/2013", @"01/06/2013", @"11/02/2013", @"01/03/2013", @"01/03/2013", @"22/05/2013", @"23/05/2013", @"27/05/2013", @"01/06/2013", @"07/07/2013", @"12/08/2013"];

NSCountedSet *set = [[NSCountedSet alloc] initWithArray:yourArray];

NSMutableDictionary *dict=[NSMutableDictionary new];

for (id obj in set) {
    [dict setObject:[NSNumber numberWithInteger:[set countForObject:obj]]
             forKey:obj]; //key is date
}

NSLog(@"Dict : %@", dict);

NSMutableArray *top3=[[NSMutableArray alloc]initWithCapacity:3];

//which dict obj is = max
if (dict.count>=3) {

    while (top3.count<3) {
        NSInteger max = [[[dict allValues] valueForKeyPath:@"@max.intValue"] intValue];

        for (id obj in set) {
            if (max == [dict[obj] integerValue]) {
                NSLog(@"--> %@",obj);
                [top3 addObject:obj];
                [dict removeObjectForKey:obj];
            }
        }
    }
}

NSLog(@"top 3 = %@", top3);

Output:

2013-11-21 20:50:45.475 Demo[19256:8c03] Dict : {
    "01/01/2013" = 3;
    "01/03/2013" = 2;
    "01/06/2013" = 2;
    "07/07/2013" = 1;
    "11/02/2013" = 1;
    "12/08/2013" = 1;
    "21/02/2013" = 1;
    "22/05/2013" = 1;
    "23/05/2013" = 1;
    "27/05/2013" = 1;
}
2013-11-21 20:50:45.476 Demo[19256:8c03] --> 01/01/2013
2013-11-21 20:50:45.477 Demo[19256:8c03] --> 01/03/2013
2013-11-21 20:50:45.477 Demo[19256:8c03] --> 01/06/2013
2013-11-21 20:50:45.478 Demo[19256:8c03] top 3 = (
    "01/01/2013",
    "01/03/2013",
    "01/06/2013"
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top