I have NSMutableArray with 50 array elements. I need to generate randomly without any repetition. Can you suggest some sample codes.
-
What type elements should be? NSNumber, int, NSString? – Ivor Prebeg Jul 20 '12 at 12:03
3 Answers
Create a local mutablearray copy of main array, and after getting random value, remove object available at random index from local array, process it till array count is 1.

- 4,739
- 1
- 19
- 35
I have assumed you want to generate numbers. This is the answer I have used for generating M random numbers from N. Though it doesn't add them into an NSMutableArray
, I'm sure you can adapt this code as required.
#define M 10
#define N 100
unsigned char is_used[N] = { 0 }; /* flags */
int in, im;
im = 0;
for (in = N - M; in < N && im < M; ++in) {
int r = rand() % (in + 1); /* generate a random number 'r' */
if (is_used[r])
/* we already have 'r' */
r = in; /* use 'in' instead of the generated number */
assert(!is_used[r]);
vektor[im++] = r + 1; /* +1 since your range begins from 1 */
is_used[r] = 1;
}
assert(im == M);
Why the above works is not immediately obvious. But it works. Exactly M numbers from [1..N] range will be picked with uniform distribution.
Note, that for large N you can use a search-based structure to store "already used" numbers, thus getting a nice O(M log M) algorithm with O(M) memory requirement.

- 1
- 1

- 31,873
- 11
- 70
- 114
here is sample to get random int less than 1000.
int y = arc4random() % 1000;
to stay without duplicates, just check before inserting

- 988
- 6
- 11
-
2It is better to use `arc4random_uniform(1000)` or whatever number, there is no modular bias. – zaph Oct 06 '14 at 01:51