Algorithm for generating anagrams