How to initialize char array with the same random character from a set of characters in Rust

1 Answer

0 votes
use std::time::{SystemTime, UNIX_EPOCH};

fn main() {
    // Get current time as a source of randomness
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("Time went backwards")
        .as_nanos();
    
    let charset: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    let charset_len = charset.len();
    
    let mut random_chars = Vec::with_capacity(10);
    
    for i in 0..10 {
        // Use a simple hash function to generate pseudo-random numbers
        let hash = ((now + i as u128 * 104729) % 104729) as usize;
        let idx = hash % charset_len;
        random_chars.push(charset[idx] as char);
    }
    
    println!("{:?}", random_chars);
}
 
      
/*
run:
   
['Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z']
     
*/

 



answered Mar 11, 2025 by avibootz
...