0
function random() internal returns (uint) {
    uint random = uint(keccak256(now, msg.sender, nonce)) % 1000;
    nonce++;
    return random;
}

In this way, you can generate random numbers, but there will be less than 100, how to solve, thank you

2

What you want is a random number within a range of 900 options.

So do this:

function random() internal returns (uint) {
    uint randomnumber = uint(keccak256(abi.encodePacked(now, msg.sender, nonce))) % 900;
    randomnumber = randomnumber + 100;
    nonce++;
    return randomnumber;
}

Basically you get a number from 0 - 899, and then add 100 to match your offset.

  • cool!!!!!!!!!!!! – Kido Oct 16 '18 at 17:34
  • BTW, notice how I changed the name of your randomnumber variable. You will want to keep it different from your function name. Additionally, you should use abi.encodePacked() before hashing the 3 values, as I have demonstrated above. – Shawn Tabrizi Oct 16 '18 at 17:35
  • why need "you should use abi.encodePacked() before hashing the 3 values"? – Kido Oct 16 '18 at 17:37
  • You can take a look here for some details: Deprecate variable argument mode of keccak256/sha256. Ultimately, it is best practice to do it this way. – Shawn Tabrizi Oct 16 '18 at 17:48
  • 4
    Be careful. That random number is 100% predictable so not suitable for a game of chance or any situation in which a participant is presumed to not be able to guess it. – Rob Hitchens - B9lab Oct 16 '18 at 18:06

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.