0

I have NSMutableArray with 50 array elements. I need to generate randomly without any repetition. Can you suggest some sample codes.

Varghese
  • 121
  • 2
  • 5
  • 15

3 Answers3

1

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.

Ankit Thakur
  • 4,739
  • 1
  • 19
  • 35
0

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.

[Source]

Community
  • 1
  • 1
James Webster
  • 31,873
  • 11
  • 70
  • 114
0

here is sample to get random int less than 1000.

int y =  arc4random() % 1000;

to stay without duplicates, just check before inserting

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