IOS: get 3 different random elements from NSMutableArray

I have an NSMutableArray of N integer elements (N> 4), I want to get 3 different random elements from this array. I do not need absolutely uniform distribution, only 3 different random elements should be in order. Do you have any suggestions? Thanks

+6
source share
4 answers

Make NSIndexSet and keep adding

 int value = arc4random() % array.count; 

to its size up to 3 . You know that you have 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]); }]; 
+10
source
 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 rest, when you accept a module with an array size, gets a value between [0, arrayCountLessOne].

If you do not want to change the original data array, you can simply make a copy of the array.

+6
source

If you want to do this several times from different places in your code, think about it: "Objective C way" is to create a category in NSMutableArray that adds the randomObjects method. The method itself should generate three random numbers from 0 to the length of the array -1 ( N-1 ), and then return a set of objects from the array at these indices in accordance with the other answers here (in particular, dasblinkenlight).

First create a category. Create a new NSMutableArray+RandomObject.h header file containing:

 @interface NSMutableArray (RandomObjects) - (NSSet *) randomObjects; @end 

<parentheses RandomElement is the name of your category. Any class you write that includes this new header file will provide all your NSMutableArray instances with the RandomElement method.

Then implementation in NSMutableArray+RandomObjects.m :

 @implementation NSMutableArray (RandomObjects) - (NSSet *) randomObjects { // Use the code from @dasblinkenlight answer here, adding the following line: return picks; } @end 

And that’s basically it. You have effectively added this feature to NSMutableArray .

+2
source

Good answer from dasblinkenlight!

In Swift 4 :

 let indexes = NSMutableIndexSet() if array.count > setSize { repeat { indexes.add(Int(arc4random_uniform(UInt32(array.count)))) } while (indexes.count < setSize) } 
0
source

Source: https://habr.com/ru/post/924933/


All Articles