Skip to content

Instantly share code, notes, and snippets.

@Ericson2314
Last active Aug 29, 2015
Embed
What would you like to do?
use std::fs::File;
use std::path::Path;
use std::io::Error;
use std::io::BufReader;
use std::io::BufRead;
use std::collections::HashMap;
use std::io::stdin;
fn sort_str(s: &str) -> String {
let mut v: Vec<char> = s.chars().collect();
v.sort();
v.into_iter().collect()
}
fn main() {
main_err().err().map(|e| panic!("{}", e));
}
fn main_err() -> std::io::Result<()> {
let path = Path::new("../word.lst");
let file = try!(File::open(&path).map_err(|why| Error::new(why.kind(),
format!("failed to open {}: {}", path.display(), why))));
let mut dict: HashMap<String, Vec<String>> = HashMap::new();
for line in BufReader::new(file).lines() {
let s = try!(line);
dict.entry(sort_str(&s)).or_insert(Vec::new()).push(s);
}
let sin = stdin();
for line in sin.lock().lines() {
let s = try!(line);
match dict.get(&sort_str(&s)) {
Some(v) => {
print!("anagrams for {}:", s);
for a in v {
print!(" {}", a);
}
println!("");
},
None => println!("no dice"),
}
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment