如何使用数字排序NSMutableArray的扑克牌

时间:2011-04-06 07:03:14

标签: iphone objective-c ios4

我有一个NSMutableArrary,它有扑克牌的形象,如:

01-13卡是黑桃,
14-26是心,
27-39是钻石,和 40-52是俱乐部。

我使用此代码按颜色对其进行排序,

[CopyArraryForShorting sortUsingSelector:@selector(caseInsensitiveCompare:)];

但是我没有按照数字排序。请告诉我如何排序。

arrayPlayerCard=[NSArray arrayWithObjects:[UIImage imageNamed:@"01.png"],
                                          [UIImage imageNamed:@"02.png"],
                        [UIImage imageNamed:@"03.png"],
                                          [UIImage imageNamed:@"04.png"],
                                          [UIImage imageNamed:@"05.png"],
                  [UIImage imageNamed:@"06.png"],
                                          [UIImage imageNamed:@"07.png"],
                                          [UIImage imageNamed:@"08.png"],........,nil];

1 个答案:

答案 0 :(得分:1)

我假设您希望卡片按严格的数字顺序排序,而不管是否合适。所以所有的A,然后是所有的两个,依此类推。

如果可能的话,我建议你建模一个卡片类,它有成员变量的价值和套装。在适当地建模数据时,明显的用例往往很容易解决。在这种情况下,这是一个很难的事实,这是一个很好的迹象,表明数据模型(带有数值的字符串不一定意味着代码之外的任何东西)是一个糟糕的。

尽管如此,您可能会遇到您拥有的数据模型,在这种情况下,您可以通过执行以下操作来实现对套装不敏感的排序:

  1. 获取每个文件名开头的数字的整数值
  2. 从这些值中减去一个,使其成为一个从零开始的编号系统
  3. 使用模块13获取卡片值(实际上卡片值减1,但这对于排序很好)
  4. 使用卡片值进行比较
  5. sortUsingFunction是你的朋友。这是一个简单的实现:

    #import <Foundation/Foundation.h>
    
    NSInteger compareCardsByValue(id a, id b, void *context) {
        // Get the integer value of the number at the start
        // of the filename
        NSInteger a_int = [(NSString*)a integerValue];
        NSInteger b_int = [(NSString*)b integerValue];
    
        // For each of the integer values, subtract one (so
        // we have a zero-based numbering system), then get
        // the value of the integer modulo 13
        a_int = (a_int - 1) % 13;
        b_int = (b_int - 1) % 13;
    
        // if you want aces to be high:
        //if (a_int == 0) a_int = 13;        
        //if (b_int == 0) b_int = 13;        
    
        // Now compare and return the appropriate value
        if (a_int < b_int) return NSOrderedAscending;
        if (a_int > b_int) return NSOrderedDescending;
        return NSOrderedSame;
    }
    
    int main (int argc, char const *argv[])
    {
        NSAutoreleasePool *arp = [[NSAutoreleasePool alloc] init];
    
        // Create a mutable array
        NSMutableArray *a = [NSMutableArray arrayWithCapacity:52];
    
        // Generate 52 image names, 01.png to 52.png, and add
        // them to the array
        for (NSInteger i = 1; i <= 52; i++) {
            NSString *imageName = [NSString stringWithFormat:@"%02i.png", i];
            [a addObject:imageName];
        }
    
        // Sort using the compareCardsByValue function
        [a sortUsingFunction:compareCardsByValue context:NULL];
    
        // Print out the resulting array
        for (NSString *s in a) {
            NSLog(@"%@", s);
        }
    
        [arp drain];
        return 0;
    }