Skip to content

Instantly share code, notes, and snippets.

@ahl
Last active November 25, 2018 07:38
Show Gist options
  • Save ahl/8b7831a7ce601b461b45 to your computer and use it in GitHub Desktop.
Save ahl/8b7831a7ce601b461b45 to your computer and use it in GitHub Desktop.
use std::fs::File;
use std::path::Path;
use std::io::BufReader;
use std::io::BufRead;
use std::collections::HashMap;
use std::io::stdin;
fn sort_str(s: &String) -> String {
let mut v: Vec<char> = s.chars().collect();
v.sort();
v.into_iter().collect()
}
fn main() {
let path = Path::new("../word.lst");
let file = match File::open(&path) {
Err(why) => panic!("failed to open {}: {}", path.display(), why),
Ok(f) => f,
};
let mut dict: HashMap<String, Vec<String>> = HashMap::new();
for line in BufReader::new(file).lines() {
let s = line.unwrap();
dict.entry(sort_str(&s)).or_insert(Vec::new()).push(s);
}
let sin = stdin();
for line in sin.lock().lines() {
let s = line.unwrap();
match dict.get(&sort_str(&s)) {
Some(v) => println!("anagrams for {}: {}", s, v.connect(" ")),
None => println!("no dice"),
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment