Example I have this array ['a', 10, 'b', 1]

I need to get result 'a' 10x more time than result 'b', randomly.

What's the most efficient way to do this in solidity?

In javascript I was creating an array like this ['a','a','a','a','a','a','a','a','a','a','b']

An then picking a random index using Math.random()

Should I use the same approach? Would that cost too much gas?

It is expected that there could be up to 1000+ items in the array if I use this method.

Note that I wouldn't need secure randomness, just pseudo randomness would be fine.

2 Answers 2


There is no such thing as a random choice in Ethereum. On the blockchain, everything must be fully reproducible on every machine that is running the node. There are some pseudo-random ways to do things, but they are all gameable (i.e. miners can cheat your contract and/or front run it in some way if it's profitable to them). When I first entered the space, people were talking about RandDAO (https://github.com/randao/randao), but I just checked the link and that project looks dead. There are also oracles to look at, but I'm not sure if they would be generating random numbers. The trouble is, every node has to have the exact same random number or they would go out of consensus.

  • 2
    I did mean pseudo randomness, I edited the title to make it more clear. Commented Jan 3, 2018 at 23:08

Let's assume that you have a solution for creating a pseudo random number in ethereum like for instance described here Any Pseudo Random Number Generator that can generate different numbers in the same block?

If you want weights, there is no need to store it in the array like you're describing above. You can simply check the thresholds. For instance, in your notation, if you have ['a', 10, 'b', 1, 'c', 2] and if your pseudo random number is uint [0, 2^256[ , you could check it like this:

if(randomUint < 10/13 * MAX_UINT) {
    // then 'a'
else if (randomUint < 11/13 * MAX_UINT) {
    // then 'a'
else {
    // then 'c'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.