Activity 19 - Explain the Anagram Finder
Below is a complete program for finding anagrams. The code is functional (for once!) - your job is to understand it.
- Take some time to explain in the in-line commments what each line of code is doing.
- In the triple /// doc-string comments before each function, explain what the function does overall and what its role is in the program.
- Consider renaming functions and variables (and if you do, replacing it elsewhere!) to make it clearer what's going on
You can pate this into your IDE/VSCode or Rust playground - whichever's easier.
Regardless of how far you get, paste your edited code into gradescope by the end of class.
use std::collections::HashMap; /// /// fn function_1(word: &str) -> Vec<char> { let mut ls: Vec<char> = Vec::new(); for ch in word.chars() { // if ch.is_alphabetic() { // let lc = ch.to_lowercase().next().unwrap(); // ls.push(lc); } } ls } /// /// fn function_2(word: &str) -> HashMap<char, usize> { let mut cs = HashMap::new(); let ls = function_1(word); for l in ls { // let c = cs.entry(l).or_insert(0); // *c += 1; } cs } /// /// fn function_3(word1: &str, word2: &str) -> bool { // let c1 = function_2(word1); // let c2 = function_2(word2); // c1 == c2 } /// /// fn function_4(word: &str) -> String { let mut ls = function_1(word); // ls.sort(); // let mut result = String::new(); for l in ls.iter() { result.push(*l); } result } /// /// fn function_5(words: Vec<&str>) -> Vec<Vec<String>> { // let mut sm: HashMap<String, Vec<String>> = HashMap::new(); for word in words { // let sig = function_4(word); // sm.entry(sig).or_insert(Vec::new()).push(word.to_string()); } // let mut g: Vec<Vec<String>> = Vec::new(); for (_s, wl) in sm { // if wl.len() > 1 { g.push(wl); } } // g.sort(); g } fn main() { let pairs = vec![ ("listen", "silent"), ("hello", "world"), ("The Morse Code", "Here come dots"), ("rust", "trust"), ("Dormitory", "Dirty room"), ]; for (w1, w2) in pairs { println!("'{}' and '{}': {}", w1, w2, function_3(w1, w2)); } println!(); let words = vec![ "listen", "silent", "enlist", "tea", "eat", "ate", "rust", "stur", "post", "stop", "pots", "tops", "hello", "world", "act", "cat", "tac", ]; let groups = function_5(words); for (i, group) in groups.iter().enumerate() { println!("Group {}: {:?}", i + 1, group); } }