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,631 questions

55,366 answers

573 users

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