I'm trying to get all the anagrams for one word with Ruby but my code doesn't work, I only get three results for the string 'ant'. Any help would be much appreciated.
class Anagram
attr_reader :word
def initialize(word)
@word = word.downcase
end
def anagram_maker
@word_bank = []
index = @word.length
minus_one = index - 1
while (index * minus_one) != 0
anagram = @word.split('').shuffle.join
@word_bank << anagram
index -= 1
end
@word_bank = @word_bank.uniq
end
def display
anagram_maker
if @word_bank.count > 1
@word_bank.each do |anagram|
puts anagram
end
else
puts "Not enough letters for an anagram"
end
end
end
Not sure what else to try here.
Your code is quite un-idiomatic Ruby.
Computing anagrams of a string is a matter of computing the permutations of the characters of the string, and Ruby makes this task quite easy. An example reproducing your
Anagram
class is:To answer your question: you get only three anagrams because the
while
loop inside theanagram_maker
method is executed three times (the length of the string). Moreover I guess that just shuffling characters is not the proper way of generating permutations, see "Algorithm to generate anagrams" for more information about implementing an anagram algorithm.