以不同的方式合并三个散列数组



我是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=>[]}
]

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

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

定义一个按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=>[]}]

创建一个简单的散列

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(的计算复杂度。

最新更新