add word scrambling (issue #290)
parent
8f18df7d88
commit
e6309177f3
@ -0,0 +1,9 @@
|
|||||||
|
[package]
|
||||||
|
name = "scramble"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
rand = "0.8.5"
|
@ -0,0 +1,38 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in new issue