Skip to content

Instantly share code, notes, and snippets.

@HarlanH
Created December 27, 2012 18:37
Show Gist options
  • Save HarlanH/4390744 to your computer and use it in GitHub Desktop.
Save HarlanH/4390744 to your computer and use it in GitHub Desktop.
draft intersect and union functions for Julia vectors
# to do set stuff with vectors, turn the B vector into a set, then
# iterate over the a vector, creating a set to remove dupes.
# This is moderately efficient, preserves order, and removes dupes.
function intersect{T}(a::Vector{T}, b::Vector{T})
bset = Set(b...)
aset = Set()
ret = T[]
for a_elem in a
if has(bset, a_elem) && !has(aset, a_elem)
push(ret, a_elem)
add(aset, a_elem)
end
end
ret
end
function union{T}(a::Vector{T}, b::Vector{T})
ret = T[]
seen = Set{T}()
for a_elem in a
if !has(seen, a_elem)
push(ret, a_elem)
add(seen, a_elem)
end
end
for b_elem in b
if !has(seen, b_elem)
push(ret, b_elem)
add(seen, b_elem)
end
end
ret
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment