Created
June 11, 2018 16:46
-
-
Save neerajkumar/45eea143b428c493a9e1495a2c3ce043 to your computer and use it in GitHub Desktop.
Counting number of anagram found in a sentence - Ruby Solution
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
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