How to generate all possible permutations of a string in Rust

1 Answer

0 votes
fn create_permutations(s: String) -> Vec<String> {
    if s.len() == 1 {
        return vec![s];
    }

    let mut permutations = Vec::new();

    for (i, c) in s.chars().enumerate() {
        let remaining = s[0..i].to_string() + &s[i+1..];
        for perm in create_permutations(remaining) {
            permutations.push(c.to_string() + &perm);
        }
    }

    permutations
}

fn main() {
    let s = "abc".to_string();
    
    let permutations = create_permutations(s);

    for perm in permutations {
        println!("{}", perm);
    }
}

 

/*
run:

abc
acb
bac
bca
cab
cba

*/

 



answered Jan 6, 2025 by avibootz
...