Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

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
...