【问题标题】:Merge three arrays of hashes in different way以不同的方式合并三个哈希数组
【发布时间】:2020-08-18 03:52:09
【问题描述】:

我是 Ruby 新手,正在尝试构建一个会议应用程序。我有三个包含哈希的数组:

  • 一个包含我安排的会议的日期,因此是一个空数组 人
  • 包含每次会议邀请的人员
  • 最后一个包含拒绝的人

这具体化为:

meetings = [
 {:id=>"1", :peoples=>[]}
 {:id=>"2", :peoples=>[]}
 {:id=>"3", :peoples=>[]}
]

invited_peoples = [
 {:id=>"1", :peoples=>['Tom', 'Henry', 'Georges', 'Nicolas']}
 {:id=>"2", :peoples=>['Arthur', 'Carl']}
]

absent_peoples = [
 {:id=>"1", :peoples=>['Henry', 'Georges']}
]

我想要:会议 + 受邀的人 - 缺席的人喜欢

meetings_with_participants = [
 {:id=>"1", :peoples=>['Tom', 'Nicolas']}
 {:id=>"2", :peoples=>['Arthur', 'Carl']}
 {:id=>"3", :peoples=>[]}
]

我正在寻找一个可读的解决方案,但我没有找到任何人......

对不起我的英语,提前谢谢你, 尼古拉斯

【问题讨论】:

  • 你尝试了什么?

标签: arrays ruby-on-rails ruby ruby-on-rails-3 hash


【解决方案1】:

创建一个简单的哈希

h = meetings.each_with_object({}) { |g,h| h[g[:id]] = g[:peoples] }
  #=> {"1"=>[], "2"=>[], "3"=>[]}

添加受邀者

invited_peoples.each { |g| h[g[:id]] += g[:peoples] }

现在

h #=> {"1"=>["Tom", "Henry", "Georges", "Nicolas"],
  #    "2"=>["Arthur", "Carl"], "3"=>[]} 

删除拒绝

absent_peoples.each { |g| h[g[:id]] -= g[:peoples] }          

现在

h #=> {"1"=>["Tom", "Nicolas"], "2"=>["Arthur", "Carl"],
  #    "3"=>[]} 

将哈希转换为哈希数组

h.map { |k,v| { :id=> k, :peoples=> v } }
  #=> [{:id=>"1", :peoples=>["Tom", "Nicolas"]},
  #    {:id=>"2", :peoples=>["Arthur", "Carl"]},
  #    {:id=>"3", :peoples=>[]}] 

我最初创建了一个哈希,只有在处理了被邀请者和拒绝者之后,我才将它转换为一个哈希数组。这样做可以加快:id 查找添加和删除人员的速度。因此,如果n = meetings.size,这些计算的计算复杂度接近O(n),“接近”是因为哈希键查找的计算复杂度接近O(1)(即定位所需的时间)一个键和它的值几乎是恒定的,不管散列的大小)。相比之下,对于meetings 的每个元素,在invited_peoplesabsent_peoples 中搜索:id 值的方法的计算复杂度为O(n2)。

【讨论】:

    【解决方案2】:

    定义一个通过id查找对象的方法

    def find_by_id array_of_hash, id
      array_of_hash.find {|x| x[:id] == id} || {peoples: []}
    end
    

    使用 map 转换一个新数组,在 map 块中使用你的逻辑 meetings + invited_peoples - absent_peoples like

    result = meetings.map do |item|
      id = item[:id]
      {id: id, peoples: item[:peoples] + find_by_id(invited_peoples, id)[:peoples] - find_by_id(absent_peoples, id)[:peoples]}
    end
    

    结果:

    => [{:id=>"1", :peoples=>["Tom", "Nicolas"]}, {:id=>"2", :peoples=>["Arthur", "Carl"]}, {:id=>"3", :peoples=>[]}]
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      • 2020-07-24
      相关资源
      最近更新 更多