Random number without repeating

前端 未结 3 1674

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

相关标签:
3条回答
  • 2020-12-22 08:45

    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.

    0 讨论(0)
  • 2020-12-22 08:45

    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]

    0 讨论(0)
  • 2020-12-22 08:46

    here is sample to get random int less than 1000.

    int y =  arc4random() % 1000;
    

    to stay without duplicates, just check before inserting

    0 讨论(0)
提交回复
热议问题