How to find maximum index over a subset of elements in julialang?

I have an array A=[3, 5, 1, 2, 7, 9, 10, 2, 3] length length(A)=9 and a set S that contains a subset of 1:9 indices, for example, S=Set([1, 3, 6, 8]) . I would like to find the maximum (value and index) of A over S That is a maximum of 9 , and an index of 6 .

I tried to do it this way

 A = [3, 5, 1, 2, 7, 9, 10, 2, 3]; S = Set([1, 3, 6, 8]); B = [if i in SA[i] else 0 end for i in 1:length(A)]; findmax(B); 

but I feel that there is a better and clever way.

+5
source share
4 answers

What about?

 julia> maximum((A[i],i) for i in S) (9, 6) 

It depends on the tuples being sorted in lexicographic order. This is just an iteration over a subset, so it should be faster when S has a significantly smaller number of elements than A

maximum is a better choice than findmax here, as Dan Getz pointed out.

+5
source

This is more detailed, but on my computer it’s about 2.5 times faster than the generator solution (version 0.6):

 function mymax(A, S) val, ind = typemin(eltype(A)), -1 for i in S val_ = A[i] if val_ > val val, ind = val_, i end end return val, ind end 
+4
source

If A would not contain duplicates (or at least the maximum was unique), I would find the following more readable:

 julia> i = findfirst(A, maximum(A[i] for i in S)) 6 julia> A[i], i (9, 6) 

maximum runs on a generator, so there should be no memory overhead. If S is small, the size of A dominates, and you still need to go through it.

+2
source

If there are more highs, you can do:

 function maximums(A,S) maxvalue = maximum(A[i] for i in S) (maxvalue, [i for i in S if A[i]==maxvalue]) end A = [3,3,3] S = Set([1,3]) maximums(A, S) # (3, [3, 1]) 

If you like to keep order and Set doesn't need a type for S, you can use the unique function:

 S = unique([1,3]) maximums(A, S) # (3, [1, 3]) 
+1
source

Source: https://habr.com/ru/post/1273055/


All Articles