不使用循环的Anagram代码

时间:2016-06-08 13:18:01

标签: ruby

dictionary = ['acres', 'cares', 'Cesar', 'races', 'smelt', 'melts', 'etlsm']

def anagrams_for(word, array)
    matches = []
    array.each do |x|
        if word.downcase.chars.sort == x.downcase.chars.sort
            matches.push(x)
        end
    end
    puts matches
end

如果输入的单词在字典中,则它应该在返回的数组中。

列表应该不区分大小写。

anagrams_for('acres', dictionary) # => ['acres', 'cares', 'Cesar', 'races']
anagrams_for('ACRES', dictionary) # => ['acres', 'cares', 'Cesar', 'races']
anagrams_for('Cesar', dictionary) # => ['acres', 'cares', 'Cesar', 'races']

虽然词典中没有"sacre",但词典中的几个词是"sacre"的字谜。

anagrams_for('sacre', dictionary) # => ['acres', 'cares', 'Cesar', 'races']

输入单词和字典中的单词都不需要是有效的英语单词。

anagrams_for('etlsm', dictionary) # => ['smelt', 'melts', 'etlsm']
anagrams_for('unicorn', dictionary) # => []

是否有一种方法不需要循环来实现相同的结果?

2 个答案:

答案 0 :(得分:1)

def anagram?(word, other)
  word.downcase.chars.sort == other.downcase.chars.sort
end

def anagrams_for(word, array)
  array.select { |other_word| anagram?(word, other_word) }
end

我不知道你是否正在寻找这个,因为select 在数组中循环。

答案 1 :(得分:1)

也许你可以在这种情况下使用哈希

def get_dictionary_hash(dictionary)
  exp = Hash.new{|k, v| k[v] = []}
  dictionary.each{|s| exp[s.downcase.chars.sort] << s}
  exp
end

def anagrams_for(word, dictionary)
  dictionary[word.downcase.chars.sort] || []
end

测试

dictionary = ['acres', 'cares', 'Cesar', 'races', 'smelt', 'melts', 'etlsm']

dictionary_h = get_dictionary_hash(dictionary)

['acres', 'ACRES', 'Cesar', 'sacre', 'etlsm', 'unicorn'].each do |word|
  puts word
  p anagrams_for(word, dictionary_h)
end

# => acres
# => ["acres", "cares", "Cesar", "races"]
# => ACRES
# => ["acres", "cares", "Cesar", "races"]
# => Cesar
# => ["acres", "cares", "Cesar", "races"]
# => sacre
# => ["acres", "cares", "Cesar", "races"]
# => etlsm
# => ["smelt", "melts", "etlsm"]
# => unicorn
# => []

我希望这会有所帮助