From 7db51ed59605b649d39850119374d048be242382 Mon Sep 17 00:00:00 2001 From: mehbark Date: Sat, 24 Aug 2024 18:23:05 -0400 Subject: [PATCH] homophones --- Cargo.toml | 2 -- src/main.rs | 38 ++++++++++++++++++++++++++++++++------ 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 76540e3..a094c66 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,5 +2,3 @@ name = "anagrams" version = "0.1.0" edition = "2021" - -[dependencies] diff --git a/src/main.rs b/src/main.rs index ef2b3fa..f3de7b7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,8 @@ -use std::{collections::HashMap, io}; +use std::{ + collections::HashMap, + fs::File, + io::{self, BufRead, BufReader}, +}; type CharCount = [u8; 26]; @@ -28,17 +32,39 @@ fn pretty_char_count(count: CharCount) -> String { } fn main() { - let mut words: HashMap> = HashMap::new(); + let mut dict: HashMap> = HashMap::new(); + // https://github.com/cmusphinx/cmudict + for line in BufReader::new(File::open("cmudict.dict").unwrap()).lines() { + let line = line.unwrap(); + if let Some((word, phos)) = line.split_once(' ') { + let word = match word.split_once('(') { + Some((word, _)) => word, + None => word, + }; + dict.entry(word.to_string()) + .or_default() + .push(phos.to_owned()); + } + } + + let mut words: HashMap<(CharCount, String), Vec> = HashMap::new(); for word in io::stdin().lines() { let word = word.unwrap(); - let count = char_count(&word); - words.entry(count).or_default().push(word); + if let Some(phos) = dict.get(&word) { + let count = char_count(&word); + for phos in phos { + words + .entry((count, phos.clone())) + .or_default() + .push(word.clone()); + } + } } - for (count, words) in words { + for ((count, phos), words) in words { if words.len() == 1 { continue; } - println!("-- {}", pretty_char_count(count)); + println!("-- {} {phos}", pretty_char_count(count)); for word in words { println!("{word}"); }