2011-04-06 34 views
0

我有一個NSMutableArrary,它擁有的撲克牌等,作爲圖像進行排序的撲克牌一個NSMutableArray:如何使用數字明智

01-13卡黑桃,
14-26的心,
27-39是鑽石,
40-52是俱樂部。

我通過顏色使用此代碼排序,

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

,但我不能給它arrary按編號排序。請告訴我如何分類。

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]; 
+0

你以爲什麼順序後,我實際上不明白,請提供一個例子。 – 2011-04-06 07:27:37

+0

你的意思是說你想把它分類好以便得到所有的ace,然後是所有的ace,等等?所以你會得到類似(僞代碼)[AH,AS,AD,AC,2H,2S,2D,2C,3H,3S ...]? – 2011-04-06 07:27:43

回答

1

我假設你想按照嚴格的數字順序排列卡片,不管西裝。所以所有的ace,然後是所有的兩個,等等。

如果可能的話,我建議你建立一個卡類,它具有值和套裝的成員變量。在適當地建模數據時,明顯的用例往往容易解決。在這種情況下這是一個困難的事實很好地表明,數據模型(帶有數值的字符串不一定代表此代碼之外的任何內容)是不好的。

不過,你可以用你的數據模型,在這種情況下,你可以通過執行實現西裝不敏感的排序被卡住了以下內容:

  1. 取數的整數值在開始每個文件名
  2. 減一的值,使之成爲零基礎的編號系統
  3. 使用模塊13到拿到卡值(實際上是卡值減去一個,不過這對於排序的罰款)
  4. 使用卡值比較

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; 
}