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

Create your online store today with Shopify

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

Disclosure: My content contains affiliate links.

43,239 questions

56,142 answers

573 users

How to find the N smallest values in a 2D vector in Rust

1 Answer

0 votes
/*
    Find the N smallest values in a 2D array.

    Approach:
    1. Flatten the 2D array into a single Vec<i32>.
    2. Sort the vector.
    3. Take the first N values.

    Rust's standard library provides fast sorting,
    and Vec makes flattening straightforward.
*/

fn flatten(matrix: &[Vec<i32>]) -> Vec<i32> {
    // Pre-allocate capacity for efficiency
    let mut flat = Vec::with_capacity(matrix.len() * matrix[0].len());

    for row in matrix {
        for &value in row {
            flat.push(value);
        }
    }

    flat
}

fn smallest_n(matrix: &[Vec<i32>], n: usize) -> Vec<i32> {
    let mut flat = flatten(matrix);

    // Sort ascending using an efficient unstable sort
    flat.sort_unstable();

    // Guard against n > total length
    let count = n.min(flat.len());

    flat[..count].to_vec()
}

fn main() {
    let matrix: Vec<Vec<i32>> = vec![
        vec![42, 12, 85,  3],
        vec![ 7, 99, 15, 23],
        vec![64,  1, 18, 30],
        vec![ 3, 55, 11, 90],
    ];

    let n: usize = 5;

    let values = smallest_n(&matrix, n);

    println!("The {} smallest values:", n);
    for v in &values {
        print!("{} ", v);
    }
}


/*
run:

The 5 smallest values:
1 3 3 7 11 

*/

 



answered Aug 10 by avibootz
...