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

51,793 answers

573 users

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

2 Answers

0 votes
use std::collections::HashSet;
 
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();
     
    let unique_hs: HashSet<i32> = v.into_iter().collect();
    let mut sorted_unique_hs: Vec<i32> = unique_hs.into_iter().collect();
    sorted_unique_hs.sort();
 
    sorted_unique_hs
}
 
fn main() {
    let arr2d = vec![
        vec![5, 6, 1, 1, 1],
        vec![3, 8, 0, 2, 2],
        vec![9, 2, 7, 3, 3],
    ];
     
    let sorted_unique_arr = arr2d_to_sorted_1d(&arr2d);
 
    for n in sorted_unique_arr {
        print!("{} ", n);
    }
}
 
  
      
/*
run:
   
0 1 2 3 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.dedup();
    
    v
}
 
fn main() {
    let arr2d = vec![
        vec![5, 6, 1, 1, 1],
        vec![3, 8, 0, 2, 2],
        vec![9, 2, 7, 3, 3],
    ];

    let sorted_unique_arr = arr2d_to_sorted_1d(&arr2d);
 
    for n in sorted_unique_arr {
        print!("{} ", n);
    }
}
 
  
      
/*
run:
   
0 1 2 3 5 6 7 8 9

*/
 

 



answered Aug 16, 2024 by avibootz
...