Generating non-repeating random numbers
I want to create a function in C. It will return a random integer in-range of N like:-
rand() % N;
but the thing is I want to keep track of uniqueness. I don't want the numbers to repeat. but i can also do this by making an array and copying the generated integers in it. like :-
array[count] = rand() % N;
and check every time if the number generated was already inside it or not. (simply by searching it inside the array[]); this is a simple approach but a correct one. it will take many if's and for's; for this to work.
this is the best i can come up with.
The thing is, I want to get the best possible/optimized solution for this problem. What will be the most efficient way to do this?
lets clear some things:- i want to set some text in a UILabel from a NSArray that is always unique. my NSArray is getting data from a Plist, and my Plist has over 1000 entries. if i want to do this many times it will effect the performance so i want some efficient way to do this.
Solution 1:
It sounds like what you want is really a random permutation of the number 1..N. So, fill an array with consecutive integers 1..N and then shuffle the array. There are well known algorithms for shuffling that you can look up.
Solution 2:
Rather than an array, you could use a super fast an efficient bloom filter. If you are generating any large quantity of numbers, this will be WAY faster than looping through an array.