【问题标题】:Counting duplicates in ruby array and storing count in hash计算 ruby​​ 数组中的重复项并将计数存储在哈希中
【发布时间】:2022-10-01 08:07:39
【问题描述】:

我有一本单词词典,我想检查给定的字符串是否包含这些单词。我希望它们存储在哈希中,键是重复的单词,值是它出现的次数。

目前,它只会存储完整的字符串匹配项(以下不计入包含单词low),实际上并不会增加重复计数。

指出我正确的方向? :)

dictionary = [\"below\",\"down\",\"go\",\"going\",\"horn\",\"how\",\"howdy\",\"it\",\"i\",\"low\",\"own\",\"part\",\"partner\",\"sit\"]

def substringer(string, dict)
  string_array = string.split(/\\W+/)
  final_hash = {}
  count = 0
  dict.each do |entry|
    if string_array.include?(entry)
      final_hash = {entry => +1}
      p final_hash
    end
  end
end

substringer(\"below, below, how\'s it goin?\", dictionary)

结果

{\"below\"=>1}
{\"how\"=>1}
{\"it\"=>1}

    标签: ruby


    【解决方案1】:

    string_array.include?(entry) 返回真,无论单词在给定数组中出现多少次。相反,请使用string_array.count(entry),它会准确地告诉您它出现了多少次。

    dict.each do |entry|
      count = string_array.count(entry)
      final_hash[entry] = count if count > 0
    end
    

    但是,这不是最有效的方法 - 因为您需要为每个字典单词迭代一次 string_array (我假设 string_array 可能比字典大得多)。尝试考虑一种迭代字符串数组的方法。

    另外,请考虑如何处理以大写字母开头的单词!

    【讨论】:

      【解决方案2】:

      让我们反转您的代码并遍历string_array 中的元素并检查dict 中是否包含。

      还使用#each_with_object 构建散列,Hash.new(0) 创建一个散列,其中键的默认值为0

      dictionary = ["below", "down", "go", "going", "horn", "how", "howdy", "it", "i", "low", "own", "part", "partner", "sit"]
      
      def substringer(string, dict)
        string_array = string.split(/\W+/)
      
        final_hash = string_array.each_with_object(Hash.new(0)) do |word, hsh|
          hsh[word] += 1 if dict.include?(word)
        end
      
        p final_hash
      end
      

      测试这个:

      substringer("below, below, how's it goin?", dictionary)
      # {"below"=>2, "how"=>1, "it"=>1}
      

      【讨论】:

        【解决方案3】:

        这是我的“单线”解决方案:

        dictionary = ["below", "down", "go", "going", "horn", "how", "howdy", "it", "i", "low", "own", "part", "partner", "sit"]
        
        str = "below, below, how's it goin?"
        
        str.split(/\W+/).tally.slice(*dictionary) #=> {"below"=>2, "how"=>1, "it"=>1}
        

        【讨论】:

          猜你喜欢
          • 2014-10-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-12-28
          • 2017-02-28
          • 1970-01-01
          • 2010-12-18
          • 1970-01-01
          相关资源
          最近更新 更多