Created
June 9, 2021 09:57
-
-
Save ttsugriy/7bf7b51a7bd61bec1ec09b69d9dff33f to your computer and use it in GitHub Desktop.
Sort words in a text
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
#![feature(test)] | |
extern crate test; | |
fn to_word_strings(text: &str) -> Vec<String> { | |
let mut start = 0; | |
let mut strings = Vec::new(); | |
for (idx, ch) in text.char_indices() { | |
if ch.is_whitespace() { | |
if idx - start > 0 { | |
strings.push(text[start..idx].to_owned()); | |
} | |
start = idx + 1; | |
} | |
} | |
if text.len() - start > 0 { | |
strings.push(text[start..text.len()].to_owned()); | |
} | |
strings | |
} | |
fn to_word_slices(text: &str) -> Vec<&str> { | |
let mut start = 0; | |
let mut slices = Vec::new(); | |
for (idx, ch) in text.char_indices() { | |
if ch.is_whitespace() { | |
if idx - start > 0 { | |
slices.push(&text[start..idx]); | |
} | |
start = idx + 1; | |
} | |
} | |
if text.len() - start > 0 { | |
slices.push(&text[start..text.len()]); | |
} | |
slices | |
} | |
fn sort_word_slices(text: &str) -> String { | |
let mut words = to_word_slices(text); | |
words.sort_unstable(); | |
words.join(" ") | |
} | |
fn sort_word_strings(text: &str) -> String { | |
let mut words = to_word_strings(text); | |
words.sort_unstable(); | |
words.join(" ") | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
use test::Bencher; | |
use rand::prelude::*; | |
#[test] | |
fn test_to_word_slices() { | |
assert_eq!(to_word_slices("hello world"), vec!["hello", "world"]); | |
} | |
#[test] | |
fn test_to_word_strings() { | |
assert_eq!( | |
to_word_strings("hello world"), | |
vec!["hello".to_owned(), "world".to_owned()] | |
); | |
} | |
#[test] | |
fn test_sort_word_slices() { | |
assert_eq!(sort_word_slices("world hello"), "hello world"); | |
assert_eq!(sort_word_slices(" world hello "), "hello world"); | |
} | |
#[test] | |
fn test_sort_word_strings() { | |
assert_eq!(sort_word_strings("world hello"), "hello world"); | |
assert_eq!(sort_word_strings(" world hello "), "hello world"); | |
} | |
#[bench] | |
fn bench_to_word_slices(bench: &mut Bencher) { | |
bench.iter(|| to_word_slices("hello world used for benchmarking")); | |
} | |
#[bench] | |
fn bench_to_word_strings(bench: &mut Bencher) { | |
bench.iter(|| to_word_strings("hello world used for benchmarking")); | |
} | |
#[bench] | |
fn bench_sort_word_slices(bench: &mut Bencher) { | |
bench.iter(|| sort_word_slices("hello world used for benchmarking")); | |
} | |
#[bench] | |
fn bench_sort_word_strings(bench: &mut Bencher) { | |
bench.iter(|| sort_word_strings("hello world used for benchmarking")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment