How to create an M x N matrix with random numbers in Rust

1 Answer

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

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

// Print matrix to console
fn print_matrix(matrix: &Vec<Vec<i32>>) {
    for row in matrix {
        for val in row {
            print!("{:4}", val);
        }
        println!();
    }
}

// Generate a rows x cols matrix filled with random integers
fn generate_random_matrix(rows: usize, cols: usize) -> Vec<Vec<i32>> {
    // 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);
    
    let mut matrix = Vec::with_capacity(rows);
    for _ in 0..rows {
        let mut row = Vec::with_capacity(cols);
        for _ in 0..cols {
            row.push(rng.random_range(0..=100));
        }
        matrix.push(row);
    }
    
    matrix
}

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



/*
run:

 100  73  33  23  35
  98  50  21  66  85
  79  81  54  81  21
  80  20  87  19  82

*/



 



answered Nov 22, 2025 by avibootz
...