coolsv
coolsv

Reputation: 781

In which array can we find elements in Julia?

Imagine we have the following array of 3 arrays, covering the range 1 to 150:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ... 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]

[51, 52, 53, 54, 55, 56, 57, 58, 59, 60 ... 92, 93, 94, 95, 96, 97, 98, 99, 100, 107]

[71, 73, 84, 101, 102, 103, 104, 105, 106, 108 ... 141, 142, 143, 144, 145, 146, 147, 148, 149, 150]

I want to build an array that stores in which array we find the values 1 to 150. The result must be then:

[1 1 1 ... 1 2 2 2 ... 2 3 2 3 2 ... 3 3 3 ... 3],

where each element corresponds to 1, 2, 3, ... ,150. The obtained array gives then the array-membership of the elements 1 to 150. The code must be applied for any number of arrays (so not only 3 arrays).

Upvotes: 0

Views: 102

Answers (2)

Jack Snow
Jack Snow

Reputation: 11

Trade memory for search in this case:

  • Make an array to record which array each value is in.
# example arrays
N=100; A=rand(1:N,30);
B = rand(1:N,40);
C = rand(1:N,35);
# record array containing each value: 
A=1,B=2,C=3; 
not found=0;
arrayin = zeros(Int32, max(maximum(A),maximum(B),maximum(C))); 
arrayin[A] .= 1; 
arrayin[B] .= 2; 
arrayin[C] .=3;

Upvotes: 1

fredrikekre
fredrikekre

Reputation: 10984

You can use an array comprehension. Here is an example with three vectors containing the range 1:10:

A = [1, 3, 4, 5, 7]
B = [2, 8, 9]
C = [6, 10]

Now we can write a comprehension using in with a fallback error to guard :

julia> [x in A ? 1 : x in B ? 2 : 3 for x in 1:10]
10-element Array{Int64,1}:
 1
 ⋮
 3

Perhaps also include a fallback error, in case the input is wrong

julia> [x in A ? 1 : x in B ? 2 : x in C ? 3 : error("not found") for x in 1:10]
10-element Array{Int64,1}:
 1
 ⋮
 3

Upvotes: 2

Related Questions