/*
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
*/