问题
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