Generating non-repeating random numbers

后端 未结 5 649
旧时难觅i
旧时难觅i 2020-11-28 00:08

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

5条回答
  •  Happy的楠姐
    2020-11-28 00:27

    Four options, all of which are O(1) in both memory and time:

    1. Just increment a global counter. Since you want uniqueness, you can't generate random numbers anyway.
    2. Generate a number from a set sufficiently large that it is highly improbable that a number repeats. 64 bits is sufficient for in-app uniqueness; 128 bits is sufficient for global uniqueness. This is how UUIDs work.
    3. If option 1 isn't "random" enough for you, use the CRC-32 hash of said global (32-bit) counter. There is a 1-to-1 mapping (bijection) between N-bit integers and their CRC-N so uniqueness will still be guaranteed.
    4. Generate numbers using a Linear Feedback Shift Register. These are N-bit counters which count in a seemingly "random" (though obviously deterministic) pattern. For your purposes, this would essentially be a modestly faster version of option 3.

提交回复
热议问题