Created
February 25, 2017 13:34
-
-
Save damonmcminn/9c5ac0798c3a4077024855cce5d137f6 to your computer and use it in GitHub Desktop.
Anagram Detector
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
| class Anagram | |
| def initialize(str) | |
| @str = str | |
| end | |
| def normalized | |
| @str.split('?').map do |word| | |
| # replace all non-alphabet characters with nothing | |
| word.downcase.gsub(/[^[:alpha:]]/, '') | |
| end | |
| end | |
| def counts | |
| normalized.map do |word| | |
| char_counts = {} | |
| word.chars.each do |char| | |
| if char_counts[char].nil? | |
| char_counts[char] = 1 | |
| else | |
| char_counts[char] += 1 | |
| end | |
| end | |
| char_counts | |
| end | |
| end | |
| def is_anagram? | |
| result = | |
| if counts.first == counts.last | |
| 'is an anagram of' | |
| else | |
| 'is NOT an anagram of' | |
| end | |
| @str.gsub('?', result) | |
| end | |
| end | |
| STDIN.readlines.each do |input| | |
| puts Anagram.new(input).is_anagram? | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment