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 num
Use some sort of hash table to store the already generated number and to fast check the number is already seen. I don't know exacltly what you are trying to do, but since you are requiring unique rand, I guess you are trying to permutate a finite set, if it is the case, have a look at some Shuffling Algorithms.
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.
Four options, all of which are O(1) in both memory and time:
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.
The algorithm described is pretty bad because it searches through the new array for each new entry. This means it has to search through more and more data as the array grows, and worse, as the number of remaining item decreases, it will end up looping more.
For example, if you have a list from 1…10, when you have filled eight items, there are only two items left (say, 7 and 9), now, each time you generate a random number, it will generate a non-unique number 80% of the time, and have to scan through at least six entries before detecting the duplicate.
There’s probably some even better methods in some libraries, but a better way than the one in the question would be to create a (linked) list of items, pick one at random, remove it, and add it to the new list. That way, every time you pick one a random one, it is guaranteed to be unique because the used ones are no longer in the pool.