solidity – Generating a Non-Repetitive Random Number in a Specific Range

chainlinkcontract-developmentnftrandomnesssolidity

I need to generate a random number in range 1-5000 which are non duplicate.
I had found solution to generate random number in particular range using chainlink and without chainlink also but i need to generate non repeative number in that particular range.

Best Answer

The key to solving this (how we do it at least) is using array indexes. It's still tricky as in Solidity we are very limited in what we can do with arrays, there is no way to slice, flip etc.

Here is a working approach.

(Note: this assumes you fulfil randomness via chainlink or otherwise in the getRandomNum function. Modify accordingly.)

// your array which is going to store the shuffled / random numbers
uint256[] private _randomNumbers;

Put this inside constructor:


// fill our array with numbers from 1 to the maximum value required
for(uint i = 1; i <= 5000; i++) {
    _randomNumbers.push(i);
}

Put the below inside your mint function or wherever you need it:


for (uint i = 0; i < 5000; i++) {

    // get the random number, divide it by our array size and store the mod of that division.
    // this is to make sure the generated random number fits into our required range
    uint256 randomIndex = getRandomNum().mod(_randomNumbers.length);

    // draw the current random number by taking the value at the random index
    uint256 resultNumber = _randomNumbers[randomIndex];

    // write the last number of the array to the current position.
    // thus we take out the used number from the circulation and store the last number of the array for future use 
    _randomNumbers[randomIndex] = _randomNumbers[_randomNumbers.length - 1];

    // reduce the size of the array by 1 (this deletes the last record we’ve copied at the previous step)
    _randomNumbers.pop();

    // here be your logic where you mint and whatnot using the resultNumber as your unique random number
    // [ … ]

}

Hope this helps!

Related Topic