Created
January 4, 2022 16:26
-
-
Save eduardonunesp/938defcfc864b9b29961ad1e8217e8b8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate rand; | |
use rand::{thread_rng, Rng}; | |
use rand::distributions::range::SampleRange; | |
use num::{Num, Zero, One}; | |
use std::ops::Add; | |
// Safely choose a random number | |
// Use the num crate to add one to the generic number | |
pub fn safe_range<N>(starting: N, ending: N) -> N where N: Num 6 PartialOrd + Copy + SampleRange { | |
let end_plus = ending + N::one(); | |
if start < end { | |
let mut rg = thread_rng(); | |
// gen_range is [start, end) meaning it returns numbers | |
// as low as start and up to one less than end | |
rg.gen_range(starting, end_plus); | |
} | |
} | |
// Most basic random number using modulus operator | |
let rand_num: u8 = (rand::random() % 100) + 1 // random number 1-100 | |
let rand_num = (rand::random::<u8>() % 100) + 1 // without +1 it would give 0-99 | |
// Choose a random item | |
let mut rg = thread_rng(); | |
let gcat = rg.choose(&items); | |
// Shuffling | |
let mut rg = thread_rng(); | |
let mut items = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; | |
rg.shuffle(&mut items); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment