Generating Non-Repeating Random Numbers

I want to create a function in C. It will return a random integer ranging from N, for example: - rand ()% N; but the fact is that I want to track uniqueness. I do not want the numbers to be repeated. but I can also do this by creating an array and copying the generated integers into it. how: - array[count] = rand() % N;and check each time if the generated number was already inside it or not. (simply by searching for it inside the array []); This is a simple approach, but correct. it will take a lot, if for; for this to work. this is the best i can think of.


The fact is that I want to get an optimal / optimized solution to this problem. What would be the most effective way to do this?

lets clarify some things: - I want to set some text in UILabel from NSArray, which is always unique. my NSArray receives data from Plist, and my Plist has over 1000 records. if I want to do this many times, this will affect performance, so I want to make an efficient way to do this.

+1
source share
5 answers

It sounds like you really are a random permutation of 1..N. So, fill the array with integers 1..N, and then shuffle the array. There are well-known shuffling algorithms that you can find.

+6
source

- . , , , , , , .

+1

. , , .

+1

, O (1) :

  • . , .
  • , , . 64 ; 128 . UUID.
  • 1 "", CRC-32 (32-) , 1--1 () N- CRC-N, - .
  • , . N- , "" ( ) . , , 3.
+1

, . , , , , .

, 1... 10, , (, 7 9), , , 80% , .

, , , , , - () , , , , , , , .

0

Source: https://habr.com/ru/post/1648467/


All Articles