How can I choose 5 random values of an array, which a function will be called upon? e.g. if I have x number of participants of a party stored in an array, how can I choose 5 random participants stored in the array who will be chosen to perform some future action?


Solidity doesn't provide random number generator. The reason for this is that solidity code must be deterministic. This means that result of its execution on every blockchain node must be identical. Therefore you can't generate random number. But there are some things you can do.

  1. You can write a function which will accept 5 inputs parameters which will be participants numbers. This means you will have to generate random numbers somewhere in your DAPP. I know it is not really answer to your questions, but sometimes it might be easier that way.
  2. You can use Oraclize.it They have a random generator you can use. Go here to see an example. It is paid service ( 0.05 USD per call ). You call their smart contract, they monitor blockchain for events. Once they see an event they run random number generator on their servers (outside of blockchain ) and then run your callback function in your smart contract. This is exactly like point 1 ( above ), but somebody does it for you and you can pay for it.
  3. You can also use block.timestamp and block.difficulty as a seed and run function like this. This will give you one random number for each transaction you mine. If you run this function twice you will get two identical numbers.
function random() private view returns (uint8) 
 return uint8(uint256(keccak256(block.timestamp, block.difficulty))%251);

Credits go to Narek Hovsepyan. His article is here.

So having one random number you can call some mathematical(whatever you choose) function which will calculate other numbers for you. This means that those 5 numbers will be related to each other, but whole set will be random.


As the hash of the last 256 blocks is globally available you can use the last five block hashes as your source of randomness.

The only issue with this is that in the same way that your contract can select the numbers, anyone watching your contract will be able to guess what numbers you will select, so if this is for a lottery or to select winners in general, it may not be an optimal solution.

You could use Oraclize and ask for five random numbers as an alternative solution.

Hope this helps.

  • actually it is to choose 5 super representatives of an 'event' smart contract to confirm that the event settings are legit. – NowsyMe Jul 14 '18 at 18:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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