enriqueqs
enriqueqs

Reputation: 59

filter elements on array present on set

I want to filter elements from an array of Int based on whether they are present another array (they are actually key values on a dictionary). What I have:

array1= [1 2 3 4 5]
array2= [1 2 3 4 5 6 7 8 9 10]

What I want (something on the lines of):

> filter!(a->a!=array1,array2)
[6 7 8 9 10]

Upvotes: 1

Views: 151

Answers (1)

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42214

You are creating a two-dimensional 1×10 Array{Int64,2} and for your case a Vector is normally more natural. Use commas (,) or perhaps if you actually have this kind of data structure drop the dimension with the [:] expression:

array1= [1, 2, 3, 4, 5]
array2= [1 2 3 4 5 6 7 8 9 10][:]

Now to filter, check id each element is in the set.

julia> filter(x -> !(x in Set(array1)), array2)
5-element Array{Int64,1}:
  6
  7
  8
  9
 10

If filtering is done many times this code can be done faster with binary search:

julia> sort!(array1);

julia> filter(x -> length(searchsorted(array1,x))==0, array2)
5-element Array{Int64,1}:
  6
  7
  8
  9
 10

Finally you can use filter! to modify the vector in-place.

Upvotes: 2

Related Questions