Controlled chaos

May 12, 2010 01:19

Sometimes you want to generate a series of random numbers in which no numbers are repeated.

After googling high and low for such a solution, I decided to write one.

Without further ado, here is a C++ function that will return "random" numbers in a sequence in which each individual number is guaranteed to be unique:

// Call this function with: 0 <= Value < Length
template
inline ValueType UniqueRandom(ValueType Value, ValueType Length)
{
    ValueType ValueOffset = 0;

while (Length > 1)
    {
        const ValueType InverseValueRemainder = ((Value + 1) & 1);
        const ValueType LengthRemainder = (Length & 1);

Value = (Value >> 1);
        Length = (Length >> 1);

ValueOffset += (InverseValueRemainder * Length);
        Length += (InverseValueRemainder * LengthRemainder);
    }

return (ValueOffset + Value);
}

Here is example output for input values [0-9] with a range of 10:

9
4
6
1
7
2
5
0
8
3
Previous post
Up