How to Random Number Generator in Solidity using keccak256

Spread the love

Wow On more time we found a good topic for my users that is Random Number Generator in Solidity using keccak256 this is our today topic, I’m sure that you know about the basic info.

Random Number Generator in Solidity using keccak256

The random numbers are numbers that occur in sequence, Here we will cover this with the following two mandatory conditions:

  • Anyone cann’t predict future values based on past outputs
  • The values distribute after every miny second

So, let’s go and see the code below and if you want to create your own random number then follow below example:

First of all Convert that hash to an uint, and then use % 100 if you want to take only the last 2 digits. This will give us a totally random number between 0 and 99.

For Example:

// Solidity program to
// demonstrate on how
// to generate a random number
pragma solidity ^0.6.6;
 
// Creating a contract
contract WholeblogsRandom
{
 
// Initializing the state variable
uint randNonce = 0;
 
// Defining a function to generate
// a random number
function randMod(uint _modulus) internal returns(uint)
{
   // increase nonce
   randNonce++; 
   return uint(keccak256(abi.encodePacked(now,
                                          msg.sender,
                                          randNonce))) % _
                                          modulus;
 }
}
Output
Random number generator solidity keccak256
                                                    Random num generator solidity keccak256

Read More: Use msg.sender in Solidity Code

Leave a Comment