r/AskComputerScience • • Sep 25 '25

Generate Random Sequence of Unique Integers From 0 to N

I'm not quite sure what sub to ask this on since it's somewhere between math and CS/programming. I would like a function that works as a generator which takes an integer from 0 to N and returns a random integer in the same range such that every value is returned exactly once. So, a 1:1 mapping from [0,N] => [0,N]. It doesn't have to be perfectly random, just mixed up to remove the correlation and avoid consecutive values. It's okay if there is some state preserved between calls.

N is an input and can be anything. If it was a power of two minus one, I could do lots of tricks with bitwise operations such as XORs.

Basically, I want something that works like the C++ standard library function std::shuffle(). But I want to be able to call this with N=1 billion without having to allocate an array of 1 billion sequential integers to start with. Runtime should scale with the number of calls to the function rather than N.

3 Upvotes

36 comments sorted by

View all comments

Show parent comment

3

u/Avereniect Sep 25 '25

I think I should clarify that I meant to suggest transforming the numbers in [0, N) via that formula. I was envisioning x being a counter that would be incremented modulo N with each call.

I don't believe that the Hull-Dobell theorem would be applicable since it appears to be predicated on the idea of using the previous output as the current value of x.

I was thinking in terms of contradiction:

Say that x_1 and x_2 are two distinct values in [0, N) where x_2 > x_1. Assume that f(x_1) = f(x_2). Then exists some value k such that ax_1 + b + kN = ax_2 + b. Rearranging this we get x_2 - x_1 = kN/a. Since N and a are coprime, this can only be true if k is a non-zero multiple of a, but then we can conclude that x_2 - x_1 >= N which isn't possible since they're both chosen from the [0, N) range, which limits their maximum difference to N - 1. Hence, the mapping produces unique outputs.

1

u/jpgoldberg Sep 25 '25 edited Sep 25 '25

Ah. I hadn't thought of x as a counter. That should take care of it. Indeed, you won't even need the increment b.

1

u/fgennari Sep 25 '25

Yes, I was treating x as a counter. This formula does appear to work for the values of N I've tested it on. Thanks for the proof.