1

我有一个将字谜放入数组数组的代码。(包含字谜)但在某处我犯了一个错误,第一个值不作为数组输出,而只是作为字符串输出

我正在使用 << 运算符将一个数组推入另一个数组,代码并不复杂,但我找不到错误

def combine_anagrams(words)
    indexes = []
    anagrams = []

    words.each{|word| 
    if(word.is_a? String )
        first_word = word.downcase.chars.sort.join
        words.each{|second_word| 
            if(second_word.is_a? String)
                if(first_word == second_word.downcase.chars.sort.join)
                    indexes << words.index(second_word)
                end
            end
        } 

        indexes.each{|index| anagrams << words[index] }
        words.reject!.with_index {|el, idx| indexes.include?(idx)}

        words << anagrams # i replaced words with an array all_anagrams
        indexes = []
        anagrams = []
    end
    }

    return words
end

puts combine_anagrams([ 'cars','for', 'potatoes', 'racs', 'four','scar', 'creams', 'scream'] ).inspect

输出

["for", "four", ["cars", "racs", "scar"], ["potatoes"], ["creams", "scream"]]

如果我在输入中切换“cars”和“for”的顺序,我会得到

["cars", "racs", "scar", ["for"], ["potatoes"], ["four"], ["creams", "scream"]]

这里发生了什么

对不起,我只是乞求学习 ruby​​ 的凌乱代码

当我将数组输出到屏幕上时,我创建了一个附加变量all_anagrams = []来存储所有字谜的all_anagrams 数组我在循环中并且这些值被跳过了吗?但是我不知道如何处理这个问题。

all_anagrams 的输出是

[["cars", "racs", "scar"], ["potatoes"], ["creams", "scream"]]
4

1 回答 1

1

您需要的是在空白之前引入一个新数组来存储字谜,让我们称之为valid_anagrams。现在你正在推动它words。正如 Fredrick 指出的那样,您在迭代单词时正在修改单词。它不好,为了避免你保留一个被调用的单词的克隆words_clone并拒绝它的项目。以下代码应该可以工作 -

def combine_anagrams(words)
    indexes, anagrams, valid_anagrams = [], [], []
    words_clone = words.clone # creating a clone of words

    words.each do |word|
            if(word.is_a? String )
                 first_word = word.downcase.chars.sort.join
                words.each do |second_word|
                        if(second_word.is_a? String)
                            if(first_word == second_word.downcase.chars.sort.join)
                                    indexes << words.index(second_word)
                            end
                        end
                end

                indexes.each{|index| anagrams << words[index] }

                # reject from words_cloned instead of words
                words_clone.reject!.with_index {|el, idx| indexes.include?(idx)}

                # insert anagrams into valid_anagrams array. In your code you inserted it in words array
                valid_anagrams << anagrams unless valid_anagrams.include?(anagrams)
                indexes, anagrams = [], []
            end
    end

    # return valid_anagrams array
    return valid_anagrams
end 
于 2012-10-15T08:01:29.067 回答