[Ethereum] Weighted Random Number Array generation in solidity

arraysrandomnesssolidity

I have an array like this in the array,

uint256[] public numberArr= [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

Each number in an array have their own weight,

uint256[] public weightNumberArr = [1, 3, 9, 7, 15, 18, 36, 22, 12, 6];

Here you can say that the weight of number 0 is 1 and for number 2 it is 3 like that. So here Chance of arriving number 6 is more than a chance of arriving number 0.

How can I generate a random number array of 0 to 9 by using weighted probability in solidity?

Any help will be highly appreciated!

Best Answer

As hinted at by Ismael in the comments your question is mostly about the algorithm and is largely answered in the linked stackoverflow question.

However the part which is special for Solidity (and Ethereum) is the randomness part. Randomness in deterministic smart contracts is a tough question - there are good and bad solutions for it.

So once you decide on how to get your random number the rest is accomplished by simply implementing the given algorithm in Solidity. The only problematic part will be gas limits if there are too many numbers - iterating over the items may result in out of gas exceptions. In that case you have to find a different algorithm.

Related Topic