2011-02-26 75 views
0

我想從目標C中的「列表」中隨機選擇x個項目,將它們存儲在其他「列表」中(每個項目只能選擇一個),我在談論列表,因爲我來自Python。在Objective C中存儲字符串列表的最佳方式是什麼?在「列表」中隨機選擇x個項目

歡呼聲,

回答

1

您應該使用NSMutableArray類多變的陣列或NSArray爲不可更改的。

UPDATE:用於從陣列中隨機選擇多個項目的一段代碼:

NSMutableArray *sourceArray = [NSMutableArray array]; 
NSMutableArray *newArray = [NSMutableArray array]; 

int sourceCount = 10; 

//fill sourceArray with some elements 
for(int i = 0; i < sourceCount; i++) { 
    [sourceArray addObject:[NSString stringWithFormat:@"Element %d", i+1]]; 
} 

//and the magic begins here :) 

int newArrayCount = 5; 

NSMutableIndexSet *randomIndexes = [NSMutableIndexSet indexSet]; //to trace new random indexes 

for (int i = 0; i < newArrayCount; i++) { 
    int newRandomIndex = arc4random() % sourceCount; 
    int j = 0; //use j in order to not rich infinite cycle 

    //tracing that all new indeces are unique 
    while ([randomIndexes containsIndex:newRandomIndex] || j >= newArrayCount) { 
     newRandomIndex = arc4random() % sourceCount; 
     j++; 
    } 
    if (j >= newArrayCount) { 
     break; 
    } 

    [randomIndexes addIndex:newRandomIndex]; 
    [newArray addObject:[sourceArray objectAtIndex:newRandomIndex]]; 
} 

NSLog(@"OLD: %@", sourceArray); 
NSLog(@"NEW: %@", newArray); 
+0

正常的,所以應該使用的NSArray用於「原始數組」從挑選和一個NSMustableArray存儲那些選定的項目。謝謝:) – 2011-02-26 11:50:53

+0

不客氣,標記爲回答如果它有幫助:) – knuku 2011-02-26 11:57:31

+0

它確實:)謝謝! – 2011-02-26 12:58:03