rustcombinationspermutationdata-generation

All possible permutations of 2 vectors on rust


Good afternoon. I have 2 vectors of unequal length

let names = vec!["Marie", "Jana", "Eva", "Anna"];
let surnames = vec!["Novakova", "Svobodova", "Novotna", "Dvorakova", "Kralova"];

How can I go through all the possible combinations of first and last names ?

Conditional 3 vector I want to get:

let gen_full_name = vec!["Marie Novakova", "Jana Novakova", "Eva Novotna", "Anna Novotna", "Jana Novakova", ...];

Solution

  • let names = vec!["Marie", "Jana", "Eva", "Anna"];
    let surnames = vec!["Novakova", "Svobodova", "Novotna", "Dvorakova", "Kralova"];
    let mut full_names = Vec::with_capacity(names.len() * surnames.len());
    for name in &names {
        for surname in &surnames {
            full_names.push(format!("{} {}", name, surname));
        }
    }
    println!("{:?}", full_names);
    

    No unnecessary allocations required.