How to initialize a matrix with random characters in Rust

1 Answer

0 votes
use rand::{Rng, SeedableRng};
use rand::rngs::StdRng;
use std::time::{SystemTime, UNIX_EPOCH};

const ROWS: usize = 3;
const COLS: usize = 4;

fn print_matrix(matrix: &Vec<Vec<char>>) {
    for row in matrix {
        for ch in row {
            // "{:>3}" gives right-aligned width of 3
            print!("{:>3}", ch);
        }
        println!();
    }
}

fn get_random_character() -> char {
    let characters: Vec<char> = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        .chars()
        .collect();
    
    // Get the current time in nanoseconds
    let seed = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("Time went backwards")
        .as_nanos() as u64;
  
    // Create a seeded RNG
    let mut rng = StdRng::seed_from_u64(seed);
    
    characters[rng.random_range(0..characters.len())]
}

fn initialize_matrix_with_random_characters(rows: usize, cols: usize) -> Vec<Vec<char>> {
    let mut matrix = Vec::with_capacity(rows);
    for _ in 0..rows {
        let mut row = Vec::with_capacity(cols);
        for _ in 0..cols {
            row.push(get_random_character());
        }
        matrix.push(row);
    }
    
    matrix
}

fn main() {
    let matrix = initialize_matrix_with_random_characters(ROWS, COLS);
    
    print_matrix(&matrix);
}



/*
run:

  5  1  G  N
  n  C  6  e
  N  k  Y  l

*/

 



answered 11 hours ago by avibootz
...