Reputation: 3464
I need to pick 32 distinctive objects from an NSMutableArray of 75 objects. it can be 1 to 32, 2 to 33 or 10 to 42. What functions should i use to get the new array? Sorry for being noob.
Upvotes: 0
Views: 110
Reputation: 55573
If you want N consecutive objects from a random index, try the following:
NSArray *arrayWithNConsecutiveObjects(NSArray *arr, int n)
{
int subIdx = arc4random_uniform((unsigned) (arr.count - n));
return [arr subarrayWithRange:NSMakeRange(subIdx, n)];
}
If you need 32 random objects, you can extend this method to randomly sort the array:
NSArray *arrayWithNObjects(NSArray *arr, int n)
{
arr = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
// random sort
return arc4random_uniform(3) - 1; // one of -1, 0, and 1
}];
int subIdx = arc4random_uniform((unsigned) (arr.count - n));
return [arr subarrayWithRange:NSMakeRange(subIdx, n)];
}
Upvotes: 3
Reputation: 133597
You can use the appropriate method inherited from NSArray
to retrieve a slice of 32 consecutive elements:
int offset = 4;
NSArray *slice = [array subarrayWithRange:NSMakeRange(offset, offset+32)];
Upvotes: 2