[Ethereum] Solidity: Choosing 5 random values of an array

contract-designcontract-developmentremixsolidity

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?

Best Answer

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.