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

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 that you have read and understand our privacy policy and code of conduct.

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