disjoint union in julia

62 views Asked by At

Is there a quick function to find the disjoint union of three or more arrays like there is union and intersect? I have searched but can't find it.

a=[1,2,3,6,7]
b=[2,3,4]
c=[3,4,5,6,7]
un=union(a,b,c)
for i in union(intersect(a,b),intersect(b,c),intersect(a,c))
    filter!(e->e!=i,un)
end

This give the correct answers un=[1,5] but surely there is a function?

1

There are 1 answers

0
Dan Getz On

The following calculates elements appearing only once in a vector list (and generalizes to more vectors):

julia> using StatsBase

julia> [k for (k,v) in countmap(Iterators.flatten([a,b,c])) if v == 1]
2-element Vector{Int64}:
 5
 1

For diversity's sake, here is a slower approach, but still succint:

first(foldl(((s1, s2), e)->(setdiff!(s1, setdiff(e, s2)),
 setdiff!(s2, e)), [a,b,c]; init=(union(a,b,c), union(a,b,c))))

This following version might actually be efficient:

foldl(flatten([a,b,c]); 
  init=(Set{eltype(a)}(),Set{eltype(a)}())) do (s1, s2), e
    e ∈ s2 && push!(s1,e)
    e ∈ s1 ? delete!(s2, e) : push!(s2, e)
    return (s1,s2)
  end |> last