I'm working on a project to find anagrams of words. My goal is to figure out the longest anagrams out there. I took a look at my code and it works but is woefully inefficient.
I have two arrays, each containing a length of long words:
words_one = ["sarcocarcinomata", "dactylopteridae", "autoradiographic", "pterylographical", "nonconversational", "pathophysiological"] words_two = ["carcinosarcomata", "pterodactylidae", "radioautographic", "pterylographical", "nonconservational", "physiopathological"]
Most of these words have to do with science, so they're relatively long.
For what I'm working on, I would like to find if all of the word pairs are anagrams of each other. In my example above, they are.
def anagrams(words_one, words_two) x = 0 while x < words_one.count if words_one[x].chars.to_a.permutation.include?(words_two[x].chars.to_a) puts 1 x += 1 else puts 0 x += 1 end end end
There are several potential problems I see here:
- Permutation Method: This sorts through all permutations of a given string. Each letter can be one of 26 different characters. This adds up real quickly.
- While Loop: I'm not sure this is the most effective method.
- Duplicate Code: I put x+=1 in both sections of my if-else block.
I'd like to learn some new techniques to optimize Ruby code.
Which type of algorithm is my code and which type of algorithm do I need?