Search code examples
randomrustidioms

Idiomatic way to get a random number that is different from a previous one?


Is there a better way to do this in Rust?

let mut current_index = rng.gen_range(0, 5);
while current_index == previous_index {
    current_index = rng.gen_range(0, 5);
}

Solution

  • Not sure about idiomatic, but this would avoid the loop:

    let current_index = (previous_index + rng.gen_range(1, 5)) % 5;