Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: does an Array contain a specific sub-array

In julia we can check if an array contains a value, like so:

> 6 in [4,6,5]
true

However this returns false, when attempting to check for a sub-array in a specific order:

> [4,6] in [4,6,5]
false

What is the correct syntax to verify if a specific sub-array exists in an array?

like image 823
Nicky Feller Avatar asked Apr 01 '16 00:04

Nicky Feller


People also ask

Are arrays mutable in Julia?

Arrays in Julia are mutable and hence it allows modification of its content. Elements in arrays can be removed or updated as per requirement.

How do you define a vector in Julia?

A Vector in Julia can be created with the use of a pre-defined keyword Vector() or by simply writing Vector elements within square brackets([]). There are different ways of creating Vector. vector_name = [value1, value2, value3,..] or vector_name = Vector{Datatype}([value1, value2, value3,..])


2 Answers

I think it is worth mentioning that in Julia 1.0 you have the function issubset

> issubset([4,6], [4,6,5])
true

You can also quite conveniently call it using the \subseteq latex symbol

> [4,6] ⊆ [4,6,5]
true

This looks pretty optimized to me:

> using Random

> x, y = randperm(10^3)[1:10^2], randperm(10^3);

> @btime issubset(x, y);
16.153 μs (12 allocations: 45.96 KiB)
like image 124
rodrigolece Avatar answered Oct 10 '22 04:10

rodrigolece


note that you can now vectorize in with a dot:

julia> in([4,6,5]).([4, 6])
2-element BitArray{1}:
 true
 true

and chain with all to get your answer:

julia> all(in([4,6,5]).([4, 6]))
true
like image 41
Adrien Avatar answered Oct 10 '22 06:10

Adrien