从基于cgfloat的表查找返回8个最接近的cgfloat

时间:2011-07-25 22:06:07

标签: iphone ios algorithm

我正在尝试创建此方法。我们称之为

-(NSMutableArray*) getEightClosestSwatchesFor:(CGFloat)hue
{
NSString *myFile = [[NSBundle mainBundle] pathForResource:@"festival101" ofType:@"plist"];
NSMutableArray* myArray = [NSArray arrayWithContentsOfFile:myFile];

for (NSDictionary *dict in myArray) 
{
    NSLog(@"[plistData valueForKey:aKey] string] is %f", [[dict valueForKey:@"hue"] floatValue]) ;

}

return myArray;

}

差不多,我正在将一个cgfloat传递给这个方法,然后需要检查一个plist文件,该文件有100个元素的hue键。我需要将我的色调与所有色调进行比较并获得最近的8个色调,最后将它们包装成一个数组并返回。

最有效的方法是什么?提前谢谢。

1 个答案:

答案 0 :(得分:0)

如果有人有兴趣,这是我的方法。随意评论它。

-(NSArray*)eightClosestSwatchesForHue:(CGFloat)hue
{

NSMutableArray *updatedArray  = [[NSMutableArray alloc] initWithCapacity:100];
NSString *myFile = [[NSBundle mainBundle] pathForResource:@"festival101" ofType:@"plist"];
NSMutableArray* myArray = [NSArray arrayWithContentsOfFile:myFile];



for (NSDictionary *dict in myArray) 
{
    CGFloat differenceHue = fabs(hue - [[dict valueForKey:@"hue"] floatValue]);
    //create  a KVA for the differenceHue here and  then add it to the dictionary and add this dictionary to the array.
    NSDictionary* tempDict = [NSDictionary dictionaryWithObjectsAndKeys:
    [dict valueForKey:@"id"], @"id",
    [NSNumber numberWithFloat:differenceHue], @"differenceHue",
     [dict valueForKey:@"color"], @"color",
    nil];

    [updatedArray addObject:tempDict]; 
}



//now we have an array of dictioneries with values we want. we need to sort this from little to big now.
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"differenceHue"  ascending:YES];
[updatedArray sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];

[descriptor release];

//now get the first 8 elements and get rid of the remaining.
NSArray *finalArray = [updatedArray subarrayWithRange:NSMakeRange(0,8)];
[updatedArray release];
return finalArray;
}