Skip to content

Instantly share code, notes, and snippets.

@chandrewz
Last active December 4, 2015 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chandrewz/14afc9f8a0b760207db3 to your computer and use it in GitHub Desktop.
Save chandrewz/14afc9f8a0b760207db3 to your computer and use it in GitHub Desktop.
Anagram
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