在“列表”中随机选择x个项目

时间:2011-02-26 10:55:48

标签: objective-c ios

我想从目标C中的“列表”中随机选择x个项目将它们存储在另一个“列表”中(每个项目只能选择一个),我说的是列表因为我要来了来自Python。在Objective C中存储字符串列表的最佳方法是什么?

欢呼声,

1 个答案:

答案 0 :(得分:1)

您应该将NSMutableArray类用于可更改的数组,或NSArray用于不可更改的数组。

更新:一段代码,用于随机选择数组中的项目数:

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