Random number without repeating

自闭症网瘾萝莉.ら 提交于 2019-11-28 12:51:50

问题


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


回答1:


here is sample to get random int less than 1000.

int y =  arc4random() % 1000;

to stay without duplicates, just check before inserting




回答2:


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.




回答3:


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]



来源:https://stackoverflow.com/questions/11578816/random-number-without-repeating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!