gpt4 book ai didi

iphone - 在 Objective-C iPhone 中按数组中的众数排序

转载 作者:行者123 更新时间:2023-12-03 20:49:17 25 4
gpt4 key购买 nike

如果我有一个 NSArray,其中包含一些值。有没有一种方法使用描述符将其按数组中最常见的数字首先排序,然后将最不常见的数字放在最后,

Array has(
"3",
"2",
"1",
"3",
"3",
"7",
)

Array has(
"3",
"3",
"3",
"1",
"2",
"7",
)

最佳答案

@interface NSArray (Ext)
-(NSArray*) sortByMostFrequent ;
@end



@implementation NSArray (Ext)
-(NSArray*) sortByMostFrequent {
NSMutableDictionary* frequencyDict = [NSMutableDictionary dictionary];
for (id obj in self) {
int frequency = [[frequencyDict valueForKey:obj] intValue];
[frequencyDict setValue:[NSNumber numberWithInt:frequency+1] forKey:obj];
}
NSMutableArray* ary = [NSMutableArray arrayWithCapacity:self.count];
for (id obj in self) {
[ary addObject:[NSDictionary dictionaryWithObjectsAndKeys:
obj, @"Object",
[frequencyDict valueForKey:obj], @"Frequency",
nil]];
}
NSSortDescriptor* sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Frequency" ascending:NO];
[ary sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
return [ary valueForKey:@"Object"];
}
@end



/// example
NSArray* ary = [NSArray arrayWithObjects:@"3", @"2", @"1", @"3", @"3", @"7", nil];
NSLog(@"ary %@", [ary sortByMostFrequent]);

关于iphone - 在 Objective-C iPhone 中按数组中的众数排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2504765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com