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

51,892 answers

573 users

How to convert a 2D vector to a 1D vector in Rust

3 Answers

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

 



answered Aug 14, 2024 by avibootz
edited Dec 27, 2024 by avibootz
0 votes
fn vec2d_to_1d(vec2d: &Vec<Vec<i32>>) -> Vec<i32> {
    let vec1d: Vec<i32> = vec2d.iter().flat_map(|x| x.iter()).cloned().collect();
       
    vec1d
}
   
fn main() {
    let vec2d = vec![
        vec![5, 6, 1, 0],
        vec![3, 8, 0, 4],
        vec![9, 2, 7, 1],
    ];
   
    let v = vec2d_to_1d(&vec2d);
   
    for n in v {
        print!("{} ", n);
    }
}
   
   
       
/*
run:
    
5 6 1 0 3 8 0 4 9 2 7 1 
    
*/

 



answered Aug 16, 2024 by avibootz
edited Dec 27, 2024 by avibootz
0 votes
fn flatten_2d_to_1d(vec_2d: &Vec<Vec<i32>>) -> Vec<i32> {
    vec_2d.iter().flatten().cloned().collect()
}

fn main() {
    let vec_2d = vec![
        vec![5, 6, 1, 8],
        vec![3, 2, 0, 4],
        vec![9, 8, 7, 6]
    ];

    let array_1d = flatten_2d_to_1d(&vec_2d);
    
    println!("{:?}", array_1d);
}




 
/*
run:
     
[5, 6, 1, 8, 3, 2, 0, 4, 9, 8, 7, 6]
     
*/

 



answered Dec 27, 2024 by avibootz

Related questions

...