From 7b1a6a93e3c309e8feaee2df1cfbe3b68b29282d Mon Sep 17 00:00:00 2001 From: boyska Date: Mon, 18 May 2020 23:56:58 +0200 Subject: [PATCH] anagrams! --- src/main.rs | 42 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/src/main.rs b/src/main.rs index 171c390..0317c14 100644 --- a/src/main.rs +++ b/src/main.rs @@ -53,20 +53,50 @@ fn line_to_word(l: String) -> String { 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 { + // 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() { let args: Vec = env::args().collect(); let fname = &args[1]; - let regexp = &args[2]; + let pattern = &args[2]; let f = File::open(fname).unwrap(); let buf = BufReader::new(&f); let mut d = Dictionary::default(); d.load_from_iterable(buf.lines()); - let re = Regex::new(regexp).unwrap(); - for w in d { - if re.is_match(w.as_str()) { - println!("{}", w) - } + //let filter = matches_regexp(pattern); + let filter = is_anagram(pattern); + for w in d.words.iter().filter(filter) { + println!("{}", w) } }