amingilani - 1 year ago 106

Ruby Question

How do we get intersections and unions in Ruby for sets that repeat elements.

`# 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"]

The

`&`

`|`

`# union without duplicates`

a | b

=> ["A", "B", "C", "D", "E"]

# intersections without duplicates

a & b

=> ["B", "C", "D"]

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

```
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"]
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**