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

51,766 answers

573 users

How to print the distinct elements of a vector in Rust

2 Answers

0 votes
use std::collections::HashMap;
 
fn count_frequency(nums: &[i32]) -> HashMap<i32, usize> {
    let mut freq = HashMap::new();
    for &num in nums {
        *freq.entry(num).or_insert(0) += 1;
    }
    freq
}
 
fn collect_uniques(freq: &HashMap<i32, usize>) -> Vec<i32> {
    let mut unique = Vec::new();
    for (&num, &count) in freq {
        if count == 1 {
            unique.push(num);
        }
    }
    unique
}
 
fn main() {
    let vector = vec![3, 5, 9, 1, 7, 8, 1, 9, 0, 3, 9];
    let freq = count_frequency(&vector);
    let mut unique = collect_uniques(&freq);
 
    unique.sort();
    println!("{:?}", unique);
}
 
  
  
/*
run:
    
[0, 5, 7, 8]
 
*/

 



answered Jul 13, 2025 by avibootz
edited Jul 13, 2025 by avibootz
0 votes
use std::collections::HashMap;

// Function to count the frequency of each number
fn count_frequency(nums: &[i32]) -> HashMap<i32, usize> {
    let mut freq = HashMap::new();
    for &num in nums {
        *freq.entry(num).or_insert(0) += 1;
    }
    freq
}

// Function to collect elements that appear only once
fn filter_unique(nums: &[i32], freq: &HashMap<i32, usize>) -> Vec<i32> {
    nums.iter()
        .filter(|&&num| freq.get(&num) == Some(&1))
        .cloned()
        .collect()
}

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

    let freq = count_frequency(&vector);
    let mut unique = filter_unique(&vector, &freq);

    unique.sort();
    println!("{:?}", unique);
}

 
 
/*
run:
   
[0, 5, 7, 8]

*/

 



answered Jul 13, 2025 by avibootz
...