ios - 对 NSMutableArray 进行排序

标签 ios arrays macos sorting

我有一个 NSMutableArray,包含 4 个对象。这些对象中的每一个都有一个名为 score 的 int 类型的属性。该数组根据该属性降序排列。这么多就好了。

现在我正在制作一个记分牌,它接受这个数组并枚举它。基本上我需要它来查看 array.score 属性并为其分配排名。

第一 - (100 分) 第二 - (90 分) 第三 - (50 分) 第四 - (10 分)

但问题是,当我在分数上有平局时,我需要它像这样出现:

第一 - (100 分) 第一 - (100 分) 第三 - (60 分) 第三 - (60 分)

基本上,我需要平局分数才能实际显示为平局。在这里的逻辑上我遇到了一些麻烦,看起来真的很简单......但我的大脑现在正在努力解决这个问题。

这是我所拥有的(这不起作用):

    // If we have the same score, the rank does not change
int rank = 1;
int rankWithTies = 1;
int previousScore = 0;


NSLog(@"------- PLAYER SCORES ------");
for (PlayerStat *stat in rotatorSorted) {

    if (stat.score < previousScore) {

        NSLog(@"A %i. Player %i - score:%i", rank, stat.playerNumber, stat.score);
        rankWithTies++;


    } else {
        previousScore = stat.score;
        NSLog(@"B %i. Player %i - score:%i", rankWithTies, stat.playerNumber, stat.score);
    }

    rank++;
}

最佳答案

通常,当你获得平局时,你实际上会跳过较低的排名——也就是说,如果你获得第二名,你的玩家将排名第一、第二、第二和第四,没有人获得第三名。我会通过做这样的事情来实现这一点:

NSUInteger rankIgnoringTies = 1;
NSUInteger rankWithTies = 1;
NSUInteger previousScore = NSUIntegerMax;

NSLog(@"------- PLAYER SCORES ------");
for (PlayerStat *stat in rotatorSorted) {
    if(stat.score < previousScore) {
        // This is not a tie, so we should move rankWithTies to the next rank.
        rankWithTies = rankIgnoringTies;
    }

    NSLog(@"%i. Player %i - score:%i", rankWithTies, stat.playerNumber, stat.score);

    previousScore = stat.score;
    rankIgnoringTies++;
}

关于ios - 对 NSMutableArray 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16725767/

相关文章:

ios - 在钥匙串(keychain)服务中使用 SecItemUpdate

ios - 核心蓝牙 : CBPeripheral disconnects every ~10 seconds

php - 在 php foreach 中明智地增加计数器状态

macos - 引导后运行的恶意 postgres 进程

ios - 字体样式在 Xcode 11 Beta 中发生更改问题

c# - 在 MonoTouch/iOS 设备 (iPhone/iPad) 上使用 protobuf-net 进行 JIT 编译错误

c++ - 嵌套 vector 与连续数组的性能影响

arrays - 如何在 O(nlogn) 和 O(n) 内查找数组中所有 "feasible"值?

objective-c - 应用程序退出事件

objective-c - NSPredicate 转义反斜杠字符