开发者

Randomly select x amount of items in a "list"

I would like to select x amount of items randomly from a "list" in objective C store them in an other "list" (each item can only be selected one) , I'm talking about lists beca开发者_开发技巧use I'm coming from Python. What would be the best way to store a list of strings in Objective C ?

cheers,


You should use NSMutableArray class for changeable arrays or NSArray for non-changeable ones.

UPDATE: a piece of code for selecting a number of items from an array randomly:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜