Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: get 3 different random elements from an NSMutableArray

I have a NSMutableArray of N Integer elements (N>4), I want to get 3 different random elements from this array. I do not really need a perfectly-uniform distribution, just 3 different random elements should be OK. Do you have any suggestion? Thanks

like image 369
DavidNg Avatar asked Sep 09 '12 00:09

DavidNg


2 Answers

Make NSIndexSet, and keep adding

int value = arc4random() % array.count;

items to it until its size gets to 3. The you know that you have your three indexes.

NSMutableIndexSet *picks = [NSMutableIndexSet indexSet];
do {
    [picks addIndex:arc4random() % array.count];
} while (picks.count != 3);
[picks enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
    NSLog(@"Element at index %ud: %@", idx, [array elementAt:idx]);
}];
like image 172
Sergey Kalinichenko Avatar answered Nov 14 '22 23:11

Sergey Kalinichenko


for (int i = 1; i <= 3; i++) {    
    int index = (int)(arc4random() % [array count]);
    id object = [array objectAtIndex:index];
    [array removeObjectAtIndex:index];
}

arc4random() returns a random number in the range [0,2^32-1). The remainder when you take the modulus with the size of the array gets you a value between [0,arrayCountLessOne].

If you don't want to change your original data array, you can just make a copy of the array.

like image 41
FeifanZ Avatar answered Nov 14 '22 23:11

FeifanZ