2

I am writing ink! contract to generate random number between min and max value. I found this article. Here we can generate random number between 0 to 99. Then I modified to generate random number between 0 to 14999. But I am testing for long time I never get value more than 252. Is there something wrong with this code? Someone please check this code. It is possible to generate random number between 0 to 14999 using this code or not?

Here is my code repo github

3
  • What specifically are you going to use the random number for? Commented Jul 21, 2023 at 14:37
  • 1
    For this @LukeSchoen
    – go11li
    Commented Jul 21, 2023 at 16:25
  • and I am following as you mentioned here
    – go11li
    Commented Jul 21, 2023 at 16:27

1 Answer 1

5

The Keccak256 hash algorithm produces a 256-bit (32-byte) hash, and its associated type Type is [u8; 32].

In your code you always take just output[0] of type u8 and your result is always less than u8::MAX, which is 255u8 as mentioned here. To use more bits from the generated hash you can change your code to something like:

let number_bytes = [output[0], output[1]];
let z = u16::from_be_bytes(number_bytes);
let number = z as u128 % (self.max_value + 1);

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.