Getting Top 10 Highest Numbers From Array?

后端 未结 5 1298
轮回少年
轮回少年 2021-01-24 23:00

I am having a bit of a issue. I have an NSMutableDictionary with 10 NSMutableArrays in it. Each array has somewhere between 0-10 numbers which could each be any integer, e.g. 12

5条回答
  •  无人及你
    2021-01-24 23:37

    Sounds like some sort of homework :)

    So you have this:

    NSMutableDictionary* source = [@{
        @"1" : @[ @10, @20, @100 … ],
        @"2" : @[ @8, @42, @17 … ]
    } mutableCopy];
    

    So lets start by creating another arrangement:

    NSMutableArray* numbers = [NSMutableArray new];
    for (NSArray* array in source.allValues)
    {
        for (NSNumber* number in array)
        {
            [numbers addObject: @{ @"number" : number, @"parent" : array }];
        }
    }
    

    This is what we get:

    @[
        @{ @"number" : @10, @"parent" :  },
        @{ @"number" : @20, @"parent" :  },
        …
    ]
    

    Now we can sort and find the numbers you wanted.

    [numbers sortUsingComparator: ^( id lhs, id rhs ){
        return [((NSDictionary*) rhs)[@"number"] compare: ((NSDictionary*) lhs)[@"number"]];
    }];
    NSArray* topNumbers = [numbers subarrayWithRange: NSMakeRange( 0, 10 )];
    

    Here we are. topNumbers contains the numbers you needed along the source array.

    This is quite a naive way to do it. It can be optimized both in CPU time and memory usage by a fair amount. But hey, keep it simple is not a bad thing.

    Not addressed: what if the tenth and eleventh numbers are equal? (adressed here: Pick Out Specific Number from Array?) range checks. not tested, not even compiled. ;)

提交回复
热议问题