Last active
December 4, 2015 16:09
-
-
Save chandrewz/14afc9f8a0b760207db3 to your computer and use it in GitHub Desktop.
Anagram
This file contains 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(anagram) | |
@anagram = anagram | |
# hash calculates # of times seen per letter | |
@hash = Hash.new | |
anagram.each_char do |c| | |
if @hash[c] | |
@hash[c] = @hash[c] + 1 | |
else | |
@hash[c] = 1 | |
end | |
end | |
end | |
def match(anagram_array) | |
result = Array.new | |
# go through each word | |
anagram_array.each do |string| | |
temp = @hash.dup | |
# go throuh each letter in word | |
string.each_char do |c| | |
# decrement our temporary hash counter | |
if temp[c] | |
temp[c] = temp[c] - 1 | |
end | |
end | |
is_anagram = true | |
# ensure our temp hash counter is all 0's | |
temp.each do |key, value| | |
if temp[key] != 0 | |
is_anagram = false | |
end | |
end | |
if is_anagram == true | |
# save the result if we deiscover an anagram | |
result.push(string) | |
end | |
end | |
return result | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment