Pick Out Specific Number from Array? [duplicate]

。_饼干妹妹 提交于 2019-12-23 04:13:21

问题


I have a bunch of NSArrays filled with numbers. Is there anyway that I can somehow grab a specific number, specifically like:

Third highest number in array, or 24th highest number in array?

But I don't want to just grab the number, I also need a reference to the index it was in the array as well, if that can be retained in the process.

Thanks.


回答1:


Third highest number in array, or 24th highest number in array?

Create a temporary copy of the array and sort it ascending.
Get the number at index 3-1 or 24-1.

I also need a reference to the index it was in the array as well

Now use indexOfObject: or indexOfObjectIdenticalTo: to get the actual index.




回答2:


Starting with the sorted numbers array from my answer here Getting Top 10 Highest Numbers From Array? :

NSUInteger wanted = 24 or anything;

NSUInteger count = 0;
NSNumber* previous = nil;
for (NSDictionary* entry in numbers)
{
    if ( wanted == 1 ) return entry;

    if (previous == nil)
    {
        // first entry
        previous = entry[@"number"];
        ++ count;

        continue;
    }

    // same number? skip it.
    if ( entry[@"number"] isEqualTo: previous ) continue;

    // if we get here, we found a different number we may be interested in

    ++ count;

    if ( count == wanted ) return entry;
}

// nothing found
return nil;

The result is a line in the numbers array from the previous question. An array of the form @[ @"number" : @<number>, @"parent" : <source array> ].



来源:https://stackoverflow.com/questions/11177585/pick-out-specific-number-from-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!