[英]Merge three arrays of hashes in different way
我是 Ruby 的新手,正在嘗試構建會議應用程序。 我有三個包含哈希的 arrays :
這體現為:
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=>[]}
]
我正在尋找一個可讀的解決方案,但我沒有找到任何人......
對不起我的英語,提前謝謝你,尼古拉斯
創建一個簡單的 hash
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"=>[]}
將 hash 轉換為哈希數組
h.map { |k,v| { :id=> k, :peoples=> v } }
#=> [{:id=>"1", :peoples=>["Tom", "Nicolas"]},
# {:id=>"2", :peoples=>["Arthur", "Carl"]},
# {:id=>"3", :peoples=>[]}]
我最初創建了一個 hash,只有在處理了受邀者和拒絕者之后,我才將其轉換為哈希數組。 這樣做可以加快:id
查找添加和刪除人員的速度。 因此,如果n = meetings.size
meeting.size ,這些計算的計算復雜度接近 O(n),“接近”,因為 hash 密鑰查找的計算復雜度接近 O(1)(即所需的時間定位一個鍵並且它的值幾乎是恆定的,不管散列的大小)。 相比之下,對於meetings
的每個元素,在invited_peoples
和absent_peoples
中搜索:id
值的方法的計算復雜度為 O(n 2 )。
def find_by_id array_of_hash, id
array_of_hash.find {|x| x[:id] == id} || {peoples: []}
end
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=>[]}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.