检查列表中的哪些单词可以来自用户输入字母

时间:2016-04-15 15:58:03

标签: arrays ruby

我试图让用户输入用逗号分隔的字母列表,并找出可以用这些字母制作的单词。该程序使用一个单词列表与输入字母进行比较。

这是我尝试过的代码。我尝试了几种不同的方式,这是我最不成功的试验。

#import list, get user input and separate each letter
list_of_words = IO.foreach("referencewords.txt")
letter_choice = gets.chomp
letter_choice = letter_choice.split(/,*/)

#make new blank array for possible words
final_word_array = []
list_of_words.each do |word|
    final_word_array.push(word) if letter_choice.include?(word)
end

#show possible words to the user
final_word_array.each do |word|
    puts word
end

当我运行此代码时,final_word_array中没有任何内容。我的问题是,为什么我没有在'final_word_array'中找到可能的单词列表?

4 个答案:

答案 0 :(得分:1)

让我们看看发生了什么。

您的letter_choice局部变量在用正则表达式分割后最终成为一个字母数组。

# assume input was "a, b, c, d"
letter_choice = "a, b, c, d"
letter_choice = letter_choice.split(/,*/) # => ['a', 'b', 'c', 'd']

稍后,您正在寻找一系列字母中的整个作品。假设你有一个单词" bad"在你的单词列表中。你会做这样的事情:

if letter_choice.include?(word)
# would be
['a', 'b', 'c', 'd'].include?("bad") # => false

因此,代码表现正常。我建议使用Set s。让list_of_words保存一组由您的单词中的字母组成的集合。然后检查你的信件是否是subset

word.subset?(letter_choice_set)

更新:忘记提及此选项不会导致重复的字母。喜欢" badd"即使用户仅输入一个" d"。

,也会匹配

答案 1 :(得分:0)

也许这可能会有所帮助:

list_of_words = IO.foreach("referencewords.txt")
letter_choice = gets.chomp.split(/,*/)

final_word_array = []
list_of_words.each do |word|
  letters_of_word = word.split('').uniq
  final_word_array.push(word) if (letters_of_word && letter_choice) == letters_of_word
end

#show possible words to the user
final_word_array.each do |word|
  puts word
end

答案 2 :(得分:0)

单词样本列表:

a = ["cat", "bat", "dog", "god", "rabbit"]

转换:

h = a.group_by{|s| s.each_char.sort}
# => {
#  ["a", "c", "t"]=>["cat"],
#  ["a", "b", "t"]=>["bat"],
#  ["d", "g", "o"]=>["dog", "god"],
#  ["a", "b", "b", "i", "r", "t"]=>["rabbit"]
#}

示例用户输入:

s = "o,d,g\n"

可能的话:

h[s.chomp.split(",").sort] # => ["dog", "god"]

答案 3 :(得分:0)

如果部分或全部字母可用于表单字词,则可以执行以下操作。

<强>代码

words_by_letters = word_list.each_with_object(Hash.new { |h,k| h[k]=[] }) { |word, h|
  h[word.each_char.sort] << word }

def extract_words(words_by_letters, letters)
  (1..letters.size).flat_map do |n|
    letters.combination(n).map(&:sort).uniq.flat_map do |word_set|
      words_by_letters[word_set]
    end.compact
  end.reject(&:empty?)
end

<强>实施例

word_list = ["a", "at", "cat", "bat", "do", "dog", "god", "act", "rot", "robot"]

words_by_letters = word_list.each_with_object(Hash.new { |h,k| h[k]=[] }) { |word, h|
  h[word.each_char.sort] << word }
  #=> {["a"]=>["a"],
  #    ["a", "t"]=>["at"],
  #    ["a", "c", "t"]=>["cat", "act"],
  #    ["a", "b", "t"]=>["bat"],
  #    ["d", "o"]=>["do"],
  #    ["d", "g", "o"]=>["dog", "god"],
  #    ["o", "r", "t"]=>["rot"],
  #    ["b", "o", "o", "r", "t"]=>["robot"]}

extract_words(words_by_letters, ['c', 'a', 't'])
  #=> ["a", "at", "cat", "act"] 

extract_words(words_by_letters, ['o', 'g', 'd'])
  #=> ["do", "dog", "god"] 

extract_words(words_by_letters, ['o', 'o', 't', 'r', 'b'])
  #=> ["rot", "robot"]