gpt4 book ai didi

ruby - Ruby 中用于具有重复元素的集合的交集和并集

转载 作者:数据小太阳 更新时间:2023-10-29 07:58:56 24 4
gpt4 key购买 nike

我们如何在 Ruby 中为重复元素的集合获取交集和并集。

# given the sets
a = ["A", "B", "B", "C", "D", "D"]
b = ["B", "C", "D", "D", "D", "E"]

# A union function that adds repetitions
union(a, b)
=> ["A", "B", "B", "C", "D", "D", "D", "E"]

# An intersection function that adds repetitions
intersection(a, b)
=> ["B", "C", "D", "D"]

如文档中所写,&| 运算符似乎会忽略重复和重复。

# union without duplicates
a | b
=> ["A", "B", "C", "D", "E"]

# intersections without duplicates
a & b
=> ["B", "C", "D"]

最佳答案

def union(a,b)
(a|b).flat_map { |s| [s]*[a.count(s), b.count(s)].max }
end

union(a,b)
# => ["A", "B", "B", "C", "D", "D", "D", "E"]

def intersection(a,b)
(a|b).flat_map { |s| [s]*[a.count(s), b.count(s)].min }
end

intersection(a,b)
#=> ["B", "C", "D", "D"]

关于ruby - Ruby 中用于具有重复元素的集合的交集和并集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37800483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com