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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,872 questions

51,796 answers

573 users

How to flatten a 2D vector into a sorted one-dimensional vector in Rust

2 Answers

0 votes
fn arr2d_to_sorted_1d(arr2d: &Vec<Vec<i32>>) -> Vec<i32> {
    let mut v = Vec::with_capacity(arr2d.len() * arr2d[0].len());
     
    for row in arr2d {
        for &val in row {
            v.push(val);
        }
    }
    
    v.sort();
     
    v
}
 
fn main() {
    let arr2d = vec![
        vec![5, 6, 1, 0],
        vec![3, 8, 0, 4],
        vec![9, 2, 7, 1],
    ];
 
    let v = arr2d_to_sorted_1d(&arr2d);
 
    for n in v {
        print!("{} ", n);
    }
}
 
 
     
/*
run:
  
0 0 1 1 2 3 4 5 6 7 8 9 
  
*/

 



answered Aug 16, 2024 by avibootz
edited Aug 16, 2024 by avibootz
0 votes
fn arr2d_to_sorted_1d(arr2d: &Vec<Vec<i32>>) -> Vec<i32> {
    let mut v: Vec<i32> = arr2d.iter().flat_map(|x| x.iter()).cloned().collect();

    v.sort();
      
    v
}
  
fn main() {
    let arr2d = vec![
        vec![5, 6, 1, 0],
        vec![3, 8, 0, 4],
        vec![9, 2, 7, 1],
    ];
  
    let v = arr2d_to_sorted_1d(&arr2d);
  
    for n in v {
        print!("{} ", n);
    }
}
  
  
      
/*
run:
   
0 0 1 1 2 3 4 5 6 7 8 9 
   
*/

 



answered Aug 16, 2024 by avibootz
...