shuffle a string in rust

To shuffle a string in Rust, you can first convert it into a mutable vector using chars() method and then shuffle it using the fisher-yates algorithm.

Here's an example implementation:

main.rs
use rand::seq::SliceRandom;

fn shuffle_string(s: &str) -> String {
    let mut chars: Vec<char> = s.chars().collect();
    let mut rng = rand::thread_rng();
    chars.shuffle(&mut rng);
    chars.iter().collect()
}

fn main() {
    let s = "example";
    let shuffled = shuffle_string(s);
    println!("{}", shuffled);
}
322 chars
15 lines

In this implementation, we first convert the input string into a mutable vector of characters using s.chars().collect(). Then, we create a ThreadRng instance in order to generate random numbers required for fisher-yates shuffle algorithm. Next we shuffle characters using the shuffle() method of the vector chars with the instance of the ThreadRng. Finally, we convert the shuffled vector of characters back to a string by iterating over it and .collect()ing the characters into a new string.

This implementation uses the SliceRandom trait to shuffle the vector chars. SliceRandom is provided by the rand crate. So, we need to include the following dependency in Cargo.toml file:

[dependencies]
rand = "0.8.4"
30 chars
3 lines

gistlibby LogSnag