Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gen_range is not able to generate 255 for an u8 type (also applies for other types) #1002

Closed
jmg-duarte opened this issue Jul 27, 2020 · 6 comments

Comments

@jmg-duarte
Copy link

jmg-duarte commented Jul 27, 2020

I'm currently developing a chip8 emulator as a learning experience and one of the instructions requires the generation of a random number between 0 and 255 (inclusive).

I am using u8 types to represent the number, currently the following code will not compile.

rand::thread_rng().gen_range(0, 256);

I understand that 256 is outside the range of u8, however this makes it impossible to generate 255.

Bellow I provide a simple example which does not compile.

use rand::prelude::*;

fn main() {
    let mut rng = rand::thread_rng();
    let v: u8 = rng.gen_range(255, 256);
    let v1: u16 = rng.gen_range(65535, 65536); // example for u16
    println!("{} {}", v, v1);
}

I'd say that a possible fix would be to provide a function which is inclusive, but I have no idea of possible challenges.

Thank you for your time!

@bjorn3
Copy link
Contributor

bjorn3 commented Jul 27, 2020

You could use rand::thread_rng().gen() instead I think.

@jmg-duarte
Copy link
Author

It does work for my use case since it covers the whole number range, however it wouldn't work if I wanted anything smaller such as [10, 255].

@vks
Copy link
Collaborator

vks commented Jul 27, 2020

gen_range does not support inclusive ranges, you have to use Uniform::new_inclusive and sample instead.

@jmg-duarte
Copy link
Author

Oh, I see.
Would the implementation of an utility method be of any use?
Or writing some documentation for this.

I'd like to help! Either approach would avoid issues like mine I guess.

@dhardy
Copy link
Member

dhardy commented Jul 27, 2020

It's related to #744 and #821 which we have yet to get around to deciding on.

@vks
Copy link
Collaborator

vks commented Aug 1, 2020

This was fixed with #1003, you can now use gen_range(a..=b).

@vks vks closed this as completed Aug 1, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants