gpt4 book ai didi

ios - 获取 3 个有序值的数组,同时支持指定值

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:29:31 24 4
gpt4 key购买 nike

抱歉,标题有点笼统,如果有人有更好的建议请告诉我。

基本上我正在编写一个自定义排行榜 View ,我只想显示 3 个分数。如果可能,它会在中间显示当前用户的分数,但如果用户位于列表的顶部或底部,它仍应显示 3 个分数,但会在列表上方或下方显示其他用户。

例如

  1. 我(如果我在最前面,则在下面显示 2)
  2. 用户 1
  3. 用户 2

  1. 用户 1
  2. 我(通常情况下我在两个分数中间)
  3. 用户 2

  1. 用户 1
  2. 用户 2
  3. 我(如果我垫底,显示比我高两分)

我编写了一个函数来完成第一部分,但没有考虑到我正在努力解决的边缘情况。任何人都可以请教吗?

-(void)getNearbyScores:(int)score{
GCLeaderboardScore *closestScoreAbove = nil; //Custom container for GC properties
GCLeaderboardScore *closestScoreBelow = nil; //Contains playerID, score, alias etc

if ([playerScores count] == 0){ //playerScores is an NSMutableDictionary
return;
}

for (NSString* key in playerScores) {

GCLeaderboardScore *playerScore = (GCLeaderboardScore *)[playerScores objectForKey:key];
if ((closestScoreAbove == nil || closestScoreAbove->score > playerScore->score) && playerScore->score > score){
closestScoreAbove = playerScore;
}
else if ((closestScoreBelow == nil || closestScoreAbove->score < playerScore->score) && playerScore->score < score){
closestScoreBelow = playerScore;
}
}

me->score = score;
me->rank = 1;
if (closestScoreAbove != nil) {
me->rank = closestScoreAbove->rank + 1;
nearbyScores = [NSMutableArray arrayWithObjects: closestScoreAbove, me, closestScoreBelow, nil];
}
else {
nearbyScores = [NSMutableArray arrayWithObjects: me, closestScoreBelow, nil];
}
}

最佳答案

假设有一个 me GCLeaderboardScore 对象,下面的方法应该返回一个包含所需 GCLeaderboardScore 对象的数组(未经测试):

-(NSArray *)getNearbyScores {

if(playerScores.count==0) return nil;

// Create an array sorted by score
NSArray *sortedByScore=[playerScores sortedArrayUsingComparator: ^(id object1, id object2) {
GCLeaderboardScore *score1=object1;
GCLeaderboardScore *score2=object2;

if(score1->score < score2->score) return NSOrderedAscending;
if(score1->score > score2->score) return NSOrderedDescending;

return NSOrderedSame;
}];

// Find index of me
NSUInteger idx=[sortedByScore indexOfObject:me];

// If me not found, return nil
if(idx==NSNotFound) return nil;

// Ideally we want to show the player before and behind
idx=MAX(0,(NSInteger)idx-1);

// maxIdx will be idx+2 or index of last object if lower
NSUInteger maxIdx=MIN(sortedByScore.count-1,idx+2);

// In case we are last, show two previous results (if array large enough)
if (maxIdx > 3)
idx=MAX(0,maxIdx-3);

// And return the objects, may be 1..3 objects
return [sortedByScore subarrayWithRange:NSMakeRange(idx,maxIdx-idx+1)];
}

关于ios - 获取 3 个有序值的数组,同时支持指定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19347516/

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