Home > OS >  Union of collection of sets in vector
Union of collection of sets in vector

Time:04-07

If I have a vector of sets, say,

vec_of_sets = [Set(vec1), Set(vec2), ..., Set(vecp)]

how do I obtain a set equal to the union of sets in the vector? That is, how can I write the following efficiently?

S1 = Set(vec1);
union!(S1, Set(vec2))
union!(S1, Set(vec3))
...
union!(S1, Set(vecp))

I don't really know where to start!

Thanks in advance.


Edit: I have tried a solution using generating functions but it doesn't work:

union(j for j in vec_of_sets)

CodePudding user response:

I guess you should use reduce:

reduce(union, vec_of_sets)

but you could also use splatting (with ...):

union(vec_of_sets...)

FWIW, you could have used splitting with your attempt, too:

union((j for j in vec_of_sets)...)

CodePudding user response:

The best and fastest approach is:

Set(Iterators.flatten(vec_of_sets))

It is around twice as fast as other possible approaches proposed at the other post and has makes than half memory allocations.

Here are some benchmarks:

julia> v = [Set(1:3), Set(2:6), Set(4:8)];

julia> @btime Set(Iterators.flatten($v));
  270.492 ns (4 allocations: 400 bytes)

julia> @btime reduce(union, $v);
  550.000 ns (11 allocations: 1.25 KiB)

julia> @btime union($v...);
  506.250 ns (11 allocations: 944 bytes)

julia> @btime union((j for j in $v)...);
  699.286 ns (15 allocations: 1.03 KiB)
  • Related