-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Refactor Anagram #825
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Refactor Anagram #825
Changes from 4 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
6cc1df1
ref: refactor anagram
sozelfist cff0c5d
chore: rename `char_frequency` to `char_count`
sozelfist 00dbb52
Merge branch 'master' into ref/string/anagram
sozelfist 7ad2b65
tests: add some edge tests
sozelfist b589d2a
style: rename local variable
vil02 b23901c
docs: remove frequency from doc-str
vil02 bd326fc
Merge branch 'master' into ref/string/anagram
vil02 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,27 +1,111 @@ | ||
| pub fn check_anagram(s: &str, t: &str) -> bool { | ||
| sort_string(s) == sort_string(t) | ||
| use std::collections::HashMap; | ||
|
|
||
| /// Custom error type representing an invalid character found in the input. | ||
| #[derive(Debug, PartialEq)] | ||
| pub enum AnagramError { | ||
| NonAlphabeticCharacter, | ||
| } | ||
|
|
||
| fn sort_string(s: &str) -> Vec<char> { | ||
| let mut res: Vec<char> = s.to_ascii_lowercase().chars().collect::<Vec<_>>(); | ||
| res.sort_unstable(); | ||
| res | ||
| /// Checks if two strings are anagrams, ignoring spaces and case sensitivity. | ||
| /// | ||
| /// # Arguments | ||
| /// | ||
| /// * `s` - First input string. | ||
| /// * `t` - Second input string. | ||
| /// | ||
| /// # Returns | ||
| /// | ||
| /// * `Ok(true)` if the strings are anagrams. | ||
| /// * `Ok(false)` if the strings are not anagrams. | ||
| /// * `Err(AnagramError)` if either string contains non-alphabetic characters. | ||
| pub fn check_anagram(s: &str, t: &str) -> Result<bool, AnagramError> { | ||
| let s_cleaned = clean_string(s)?; | ||
| let t_cleaned = clean_string(t)?; | ||
|
|
||
| Ok(char_count(&s_cleaned) == char_count(&t_cleaned)) | ||
| } | ||
|
|
||
| /// Cleans the input string by removing spaces and converting to lowercase. | ||
| /// Returns an error if any non-alphabetic character is found. | ||
| /// | ||
| /// # Arguments | ||
| /// | ||
| /// * `s` - Input string to clean. | ||
| /// | ||
| /// # Returns | ||
| /// | ||
| /// * `Ok(String)` containing the cleaned string (no spaces, lowercase). | ||
| /// * `Err(AnagramError)` if the string contains non-alphabetic characters. | ||
| fn clean_string(s: &str) -> Result<String, AnagramError> { | ||
| s.chars() | ||
| .filter(|c| !c.is_whitespace()) | ||
| .map(|c| { | ||
| if c.is_alphabetic() { | ||
| Ok(c.to_ascii_lowercase()) | ||
| } else { | ||
| Err(AnagramError::NonAlphabeticCharacter) | ||
| } | ||
| }) | ||
| .collect() | ||
| } | ||
|
|
||
| /// Computes the frequency of characters in a string. | ||
| /// | ||
| /// # Arguments | ||
| /// | ||
| /// * `s` - Input string. | ||
| /// | ||
| /// # Returns | ||
| /// | ||
| /// * A `HashMap` where the keys are characters and values are their frequencies. | ||
| fn char_count(s: &str) -> HashMap<char, usize> { | ||
| let mut freq = HashMap::new(); | ||
| for c in s.chars() { | ||
| *freq.entry(c).or_insert(0) += 1; | ||
| } | ||
| freq | ||
vil02 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn test_check_anagram() { | ||
| assert!(check_anagram("", "")); | ||
| assert!(check_anagram("A", "a")); | ||
| assert!(check_anagram("anagram", "nagaram")); | ||
| assert!(check_anagram("abcde", "edcba")); | ||
| assert!(check_anagram("sIlEnT", "LiStEn")); | ||
|
|
||
| assert!(!check_anagram("", "z")); | ||
| assert!(!check_anagram("a", "z")); | ||
| assert!(!check_anagram("rat", "car")); | ||
| macro_rules! test_cases { | ||
| ($($name:ident: $test_case:expr,)*) => { | ||
| $( | ||
| #[test] | ||
| fn $name() { | ||
| let (s, t, expected) = $test_case; | ||
| assert_eq!(check_anagram(s, t), expected); | ||
| assert_eq!(check_anagram(t, s), expected); | ||
| } | ||
| )* | ||
| } | ||
| } | ||
|
|
||
| test_cases! { | ||
| empty_strings: ("", "", Ok(true)), | ||
| empty_and_non_empty: ("", "Ted Morgan", Ok(false)), | ||
| single_char_same: ("z", "Z", Ok(true)), | ||
| single_char_diff: ("g", "h", Ok(false)), | ||
| valid_anagram_lowercase: ("cheater", "teacher", Ok(true)), | ||
| valid_anagram_with_spaces: ("madam curie", "radium came", Ok(true)), | ||
| valid_anagram_mixed_cases: ("Satan", "Santa", Ok(true)), | ||
| valid_anagram_with_spaces_and_mixed_cases: ("Anna Madrigal", "A man and a girl", Ok(true)), | ||
| new_york_times: ("New York Times", "monkeys write", Ok(true)), | ||
| church_of_scientology: ("Church of Scientology", "rich chosen goofy cult", Ok(true)), | ||
| mcdonalds_restaurants: ("McDonald's restaurants", "Uncle Sam's standard rot", Err(AnagramError::NonAlphabeticCharacter)), | ||
| coronavirus: ("coronavirus", "carnivorous", Ok(true)), | ||
| synonym_evil: ("evil", "vile", Ok(true)), | ||
| synonym_gentleman: ("a gentleman", "elegant man", Ok(true)), | ||
| antigram: ("restful", "fluster", Ok(true)), | ||
| sentences: ("William Shakespeare", "I am a weakish speller", Ok(true)), | ||
| part_of_speech_adj_to_verb: ("silent", "listen", Ok(true)), | ||
| anagrammatized: ("Anagrams", "Ars magna", Ok(true)), | ||
| non_anagram: ("rat", "car", Ok(false)), | ||
| invalid_anagram_with_special_char: ("hello!", "world", Err(AnagramError::NonAlphabeticCharacter)), | ||
| invalid_anagram_with_numeric_chars: ("test123", "321test", Err(AnagramError::NonAlphabeticCharacter)), | ||
| invalid_anagram_with_symbols: ("check@anagram", "check@nagaram", Err(AnagramError::NonAlphabeticCharacter)), | ||
| non_anagram_length_mismatch: ("abc", "abcd", Ok(false)), | ||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.