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

1 Answer

0 votes
use std::collections::BTreeSet;

// Function that flattens a 2D vector, sorts it, removes duplicates,
// and returns a new sorted vector with unique values
fn flatten_sort_unique(vec2d: Vec<Vec<i32>>) -> Vec<i32> {

    // 1. Flatten the 2D vector into a 1D vector
    let mut flat: Vec<i32> = Vec::new();
    for row in vec2d {
        flat.extend(row);
    }

    // 2. Insert into BTreeSet to sort and remove duplicates
    let set: BTreeSet<i32> = flat.into_iter().collect();

    // 3. Convert back to Vec
    set.into_iter().collect()
}

fn main() {
    let vec2d: Vec<Vec<i32>> = vec![
        vec![4, 3, 3, 2, 4],
        vec![30, 10, 10],
        vec![10, 30],
        vec![1, 1, 6, 7, 7, 7, 8],
    ];

    let arr = flatten_sort_unique(vec2d);

    // Print results
    for n in arr {
        print!("{}\t", n);
    }
}



/*
run

1	2	3	4	6	7	8	10	30	

*/

 



answered 3 hours ago by avibootz

Related questions

...