Solidity

想要生成特定範圍內的非重複隨機數

  • January 16, 2022

我需要在 1-5000 範圍內生成一個不重複的隨機數。我找到了使用鏈環和不使用鏈環在特定範圍內生成隨機數的解決方案,但我需要在該特定範圍內生成非重複數。

解決這個問題的關鍵(至少我們是如何做到的)是使用數組索引。這仍然很棘手,因為在 Solidity 中,我們對數組的處理非常有限,無法切片、翻轉等。

這是一種工作方法。

(注意:這假設您通過鏈環或其他方式在getRandomNum函式中實現隨機性。相應地修改。)

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

把它放在建構子中:


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

將以下內容放入您的 mint 函式或任何您需要的地方:


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
   // [ … ]

}

希望這可以幫助!

引用自:https://ethereum.stackexchange.com/questions/118934