amingilani - 4 months ago 11x

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

Answer

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

Source (Stackoverflow)

Comments