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

2

u/jpgoldberg Sep 25 '25

Yeah. The article really isn’t aimed at your case. It really isn’t aimed at anything, as it really was me going through my own learning process. But there are conditions beyond the multiplier and the modulus being coprime.

Using a large prime will help, and if you pick one that is larger than N/2, you won’t have to worry N being a multiple of the prime that you pick, otherwise you still have to check that they are coprime. But picking primes at random is more work than just picking numbers at random and rejecting those that aren’t co-prime.

I’m not promising anything, but I might read over what I’ve written and see if I can come up with a nice way to create the generator.