commit 9847d79b6dabbc578abe9480ac1c785a8670a2d2 Author: mehbark Date: Sat Aug 24 17:16:17 2024 -0400 anagram diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..04ecc5f --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "anagrams" +version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..76540e3 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "anagrams" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..ef2b3fa --- /dev/null +++ b/src/main.rs @@ -0,0 +1,46 @@ +use std::{collections::HashMap, io}; + +type CharCount = [u8; 26]; + +fn char_count(word: &str) -> CharCount { + let mut count = [0; 26]; + for c in word.bytes() { + if !c.is_ascii_alphabetic() { + continue; + } + let idx = c.to_ascii_lowercase() - b'a'; + count[idx as usize] += 1; + } + count +} + +fn pretty_char_count(count: CharCount) -> String { + let mut out = String::new(); + for (i, count) in count.into_iter().enumerate() { + if count > 0 { + if count > 1 { + out.push_str(&count.to_string()); + } + out.push((i as u8 + b'a') as char); + } + } + out +} + +fn main() { + let mut words: HashMap> = HashMap::new(); + for word in io::stdin().lines() { + let word = word.unwrap(); + let count = char_count(&word); + words.entry(count).or_default().push(word); + } + for (count, words) in words { + if words.len() == 1 { + continue; + } + println!("-- {}", pretty_char_count(count)); + for word in words { + println!("{word}"); + } + } +}