Rust Program to Compute all the permutations of the string


Compute all the permutations of the string

Rust Programming Language


Compute all the permutations of the string


Problem


In Rust, we can use the itertools crate to compute all the permutations of a given string. Here's an example program that demonstrates how to do this.

Input


use itertools::Itertools;

fn main() {
    let input = "abc";

    let permutations = input.chars().permutations(input.len());

    for permutation in permutations {
        let string = permutation.into_iter().collect::<String>();
        println!("{}", string);
    }
}{codeBox}


Output


The output of this program will be all the permutations of the input string "abc", in this case:

abc
acb
bac
bca
cab
cba{codeBox}


Explanation


In this program, we first import the Itertools trait from the itertools crate. We then define a String input variable containing the string for which we want to compute permutations.

Next, we use the chars() method to convert the input string into an iterator of characters. We then call the permutations() method on the iterator, passing in the length of the input string. This generates an iterator of permutations of the input string.

We then loop through each permutation and convert it back into a string using the into_iter() and collect() methods. Finally, we print the resulting string to the console.



Post a Comment