我正在尝试计算NSArray中一组(小)NSNumbers的中位数。 NSArray中的每个对象都是NSNumber。
这是我正在尝试的,但它不起作用:
NSNumber *median = [smallNSArray valueForKeyPath:@"@median.floatValue"];
答案 0 :(得分:23)
NSArray *sorted = [smallNSArray sortedArrayUsingSelector:@selector(compare:)]; // Sort the array by value
NSUInteger middle = [sorted count] / 2; // Find the index of the middle element
NSNumber *median = [sorted objectAtIndex:middle]; // Get the middle element
你可以变得更加漂亮。例如,具有偶数个数的集合的中值在技术上是中间两个数字的平均值。您还可以将其打包成NSArray
上的类别中的整齐单行方法:
@interface NSArray (Statistics)
- (id)median;
@end
@implementation NSArray (Statistics)
- (id)median
{
return [[self sortedArrayUsingSelector:@selector(compare:)] objectAtIndex:[self count] / 2];
}
@end
答案 1 :(得分:6)
对于那些对此功能有不寻常需求的人,这里有一个NSArray上的类别方法,它可以同时使用奇数和偶数元素:
- (float)median {
if (self.count == 1) return [self[0] floatValue];
float result = 0;
NSUInteger middle;
NSArray * sorted = [self sortedArrayUsingSelector:@selector(compare:)];
if (self.count % 2 != 0) { //odd number of members
middle = (sorted.count / 2);
result = [[sorted objectAtIndex:middle] floatValue];
}
else {
middle = (sorted.count / 2) - 1;
result = [[@[[sorted objectAtIndex:middle], [sorted objectAtIndex:middle + 1]] valueForKeyPath:@"@avg.self"] floatValue];
}
return result;
}
NSArray * singleElement = @[@1];
NSArray * oddNumberOfElements = @[@3, @5, @7, @12, @13, @14, @19, @20, @21, @22, @23, @29, @39, @40, @56];
NSArray * evenNumberOfElements = @[@3, @5, @7, @12, @13, @14, @19, @20, @21, @22, @23, @29, @40, @56];
NSLog(
@"oddNumberOfElements: %f, evenNumberOfElements: %f singleElement: %f",
[oddNumberOfElements median], [evenNumberOfElements median], [singleElement median]
);
//oddNumberOfElements: 20.000000, evenNumberOfElements: 19.500000 singleElement: 1.000000
答案 2 :(得分:3)
快速扩展
extension Array where Element: Comparable {
var median: Element {
return self.sort(<)[self.count / 2]
}
}