2011-02-26 66 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

相关问题