Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Ruby-bang方法时,匹配英语单词算法停止工作_Ruby_Algorithm - Fatal编程技术网

使用Ruby-bang方法时,匹配英语单词算法停止工作

使用Ruby-bang方法时,匹配英语单词算法停止工作,ruby,algorithm,Ruby,Algorithm,我正在编写一个匹配算法,将用户输入的单词与一个巨大的英语单词列表进行对比,看看它能找到多少匹配项。一切都正常,除了我有两行代码,这两行代码基本上不需要两次选择同一个字母,它们使整个过程只返回一个字母。以下是我所做的: word_array = [] File.open("wordsEn.txt").each do |line| word_array << line.chomp end puts "Please enter a string of characters wi

我正在编写一个匹配算法,将用户输入的单词与一个巨大的英语单词列表进行对比,看看它能找到多少匹配项。一切都正常,除了我有两行代码,这两行代码基本上不需要两次选择同一个字母,它们使整个过程只返回一个字母。以下是我所做的:

word_array = []

File.open("wordsEn.txt").each do |line|
    word_array << line.chomp
end

puts "Please enter a string of characters with no spaces:"
user_string = gets.chomp.downcase

user_string_array = user_string.split("")

matching_words = []

word_array.each do |word|
    one_array = word.split("")

    tmp_user_string_array = user_string_array

    letter_counter = 0

    for i in 0...word.length
        if tmp_user_string_array.include? one_array[i]
            letter_counter += 1

            string_index = tmp_user_string_array.index(one_array[i])
            tmp_user_string_array.slice!(string_index)
        end
    end

    if letter_counter == word.length
        matching_words << word
    end
end

puts matching_words

有人能看到这里的问题吗?这一切对我来说都很有意义。

我知道发生了什么。您正在删除不匹配单词的字母,这会阻止找到匹配的单词

例如,以这个单词列表为例:

ant
bear
cat
dog
emu
这是您程序的输入:

catdog
您查找的第一个单词是
ant
,这会导致
a
t
catdog
中被切掉,留下
cdog
。现在无法再找到单词
cat

解决方法是确保您的
tmp\u user\u string\u数组
确实是一个临时数组。目前,它是对原始
用户字符串数组的引用,这意味着您正在破坏性地修改用户输入。你应该在开始切片和切割之前复制一份


一旦这项工作开始,您可能想考虑更有效的方法,不需要复制和切片阵列。想想看:如果你在开始寻找一个匹配之前,对你的词典的每个词以及输入字符串进行排序?这将把单词
cat
变成
act
,把输入的
acatdog
变成
aacdgot
。您看到了如何在不需要进行任何切片的情况下遍历已排序的单词和已排序的输入来搜索匹配项了吗?

如果您将
tmp\u user\u string\u array=user\u string\u array
更改为
tmp\u user\u string\u array=user\u string\u array.dup
可能会有所帮助吗?目前,两个变量通过引用引用同一个数组,因此可以有效地对两个数组进行切片。
dup
应该能解决这个问题。事实上,这对Henrik真的很有帮助,非常感谢!这不是答案,所以我把它作为一个注释,它可能会更快,而且需要更少的代码来将单词存储在(请参阅)数组中,而不是数组中。非常感谢,这太棒了!我很感激你在回答中所说的细节。
catdog