Skip to content

Instantly share code, notes, and snippets.

@wperron
Created March 7, 2023 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wperron/7fe1252c1f19c156a56ea45ddc8c4dbf to your computer and use it in GitHub Desktop.
Save wperron/7fe1252c1f19c156a56ea45ddc8c4dbf to your computer and use it in GitHub Desktop.
scramble string, but still readable
use rand::seq::SliceRandom;
/// If you mix up the order of letters in a word, many people can slitl raed and urenadnstd tehm. Write a function that
/// takes an input sentence, and mixes up the insides of words (anything longer than 3 letters).
///
/// Example:
///
/// ```
/// > scramble(["A quick brown fox jumped over the lazy dog."])
/// > "A qciuk bwron fox jmepud oevr the lzay dog."
/// ```
fn main() {
let mut sentence = "A quick brown fox jumped over the lazy dog.".to_string();
scramble(&mut sentence);
println!("{}", sentence);
}
fn scramble(sentence: &mut String) {
let mut i = 0;
while i < sentence.len() {
if let Some(word_len) = sentence.get(i..).unwrap().find(' ') {
if word_len >= 4 {
let inner = sentence.get_mut(i + 1..i + word_len - 1).unwrap();
// shuffle it
let mut rng = rand::thread_rng();
unsafe {
inner.as_bytes_mut().shuffle(&mut rng);
}
}
i = i + word_len + 1;
} else {
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment