Skip to content

Commit c692c24

Browse files
committed
find all the anagrams of a word from a given list
1 parent ddc623e commit c692c24

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

beginners/anagrams.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Write a function that will find all the anagrams of a word from a given list (array of words). You should return an empty array if there is no anagram.
2+
3+
def anagrams(word, words)
4+
hash={}
5+
('a'..'z').each {|i| hash[i] = 0}
6+
word.each_char {|i| hash[i]+=1 }
7+
8+
words.collect do |w|
9+
tmp={}
10+
('a'..'z').each {|i| tmp[i] = 0}
11+
w.each_char {|i| tmp[i]+=1 }
12+
w if tmp==hash
13+
end.compact
14+
end
15+
16+
17+
print anagrams('abbabc', ['aabbbc', 'ababcc', 'bbaabc', 'ababac'])
18+
puts ""
19+
print anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer'])

0 commit comments

Comments
 (0)