Created
March 7, 2023 14:41
-
-
Save wperron/7fe1252c1f19c156a56ea45ddc8c4dbf to your computer and use it in GitHub Desktop.
scramble string, but still readable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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