Skip to content

Instantly share code, notes, and snippets.

@neerajkumar
Created June 11, 2018 16:46
Show Gist options
  • Save neerajkumar/45eea143b428c493a9e1495a2c3ce043 to your computer and use it in GitHub Desktop.
Save neerajkumar/45eea143b428c493a9e1495a2c3ce043 to your computer and use it in GitHub Desktop.
Counting number of anagram found in a sentence - Ruby Solution
require 'byebug'
class AnagramCountChecker
def initialize(str)
@str = str
end
def sort_word(word)
word.chars.sort_by { |ch| ch.ord }.join('')
end
def number_of_anagrams
anagram_hash = {}
@str.split(' ').each do |word|
sorted_word = sort_word(word.gsub(',', '').strip)
if anagram_hash.has_key?(sorted_word)
anagram_hash[sorted_word] = 1
else
anagram_hash[sorted_word] = 0
end
end
return anagram_hash.values.sum
end
end
puts AnagramCountChecker.new('I saw this in aws, listen this was silent').number_of_anagrams()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment