anagrams!

This commit is contained in:
boyska 2020-05-18 23:56:58 +02:00
parent 241114c895
commit 7b1a6a93e3

View file

@ -53,20 +53,50 @@ fn line_to_word(l: String) -> String {
l l
} }
// filtri {{{
// i filtri dovrebbero essere creati da una struct Config{} creata parsando gli argomenti
fn matches_regexp(regexp: &str) -> (impl std::ops::FnMut(&&String) -> bool) {
// filtro
let re = Regex::new(regexp).unwrap();
move |w| re.is_match(w.as_str())
}
fn sort_word(word: &str) -> Result<String, impl std::error::Error> {
// funzione ausiliaria, utile per la is_anagram e cose simili
// ritorna una COPIA
// esempio: house -> ehosu
let mut w_bytes = word.to_string().clone().into_bytes();
w_bytes.sort();
String::from_utf8(w_bytes)
}
fn is_anagram(word: &str) -> (impl std::ops::FnMut(&&String) -> bool) {
// filtro
let sorted_word = sort_word(word).unwrap();
move |w| {
sorted_word == sort_word(w.as_str()).unwrap()
}
}
// filtri }}}
fn main() { fn main() {
let args: Vec<String> = env::args().collect(); let args: Vec<String> = env::args().collect();
let fname = &args[1]; let fname = &args[1];
let regexp = &args[2]; let pattern = &args[2];
let f = File::open(fname).unwrap(); let f = File::open(fname).unwrap();
let buf = BufReader::new(&f); let buf = BufReader::new(&f);
let mut d = Dictionary::default(); let mut d = Dictionary::default();
d.load_from_iterable(buf.lines()); d.load_from_iterable(buf.lines());
let re = Regex::new(regexp).unwrap(); //let filter = matches_regexp(pattern);
for w in d { let filter = is_anagram(pattern);
if re.is_match(w.as_str()) { for w in d.words.iter().filter(filter) {
println!("{}", w) println!("{}", w)
}
} }
} }