Rust question: How do I pick 2 different elements from a range? My code look like this:…
- User
Rust question:
How do I pick 2 different elements from a range?
My code look like this: let color0: u8 = rng.gen_range(0..=9); let mut color1: u8 = color0; while color1 == color0 { color1 = rng.gen_range(0..=9); }
Is there a nicer way
Assistant
Yes, there is a nicer way to pick 2 different elements from a range in Rust. You can use the
choosefunction from therand::Rngtrait, which chooses a random element from the range without replacement:use rand::prelude::*; let mut rng = StdRng::new(); // Create a new random number generator let color0: u8 = rng.gen_range(0..=9); // Choose a random color from the range let color1: u8 = rng.choose(&[0..=9]); // Choose a different random color from the rangeIn the
choosefunction, you can pass a range expression or any other type that implements theRandomSizeandSampletraits.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.