Finding a vector which has the sum of the indices which are prime numbers

For example a=[1 2 3; 4 5 6; 7 8 9] indices are ((1,1) ,(1,2) , (1,3); (2,1),(2,2),(2,3); (3,1),(3,2),(3,3)) and the prime number of these sums are 2,3,5 which should be in the vector s. Is there any function in julia which returns indices besides findmin and findmax? it should also be solved without for and if loops.

Just some hint:
findall takes a function, which, if returns true for an element of an array, returns the indices of all these element.

findall(f::Function, A)

One alternative is to look into CartesianIndices in combination with logical indexing.

For me the problem is not well defined yet. The sum of the indices or of the values (if the indices, the values have any relevance here?), if the indices are Cartesian indexes as it seems to be the case, how do you sum them? The final result is a 2-tuple of summed values or a single value?

sum of indices, i thnik the value is important beacuse u have to return it as a vector

I’m pretty sure the problem is well-defined. But I don’t want to post a solution because it appears to be an exam question.

5 Likes

I understand the exam is over. The approach here is to use CartesianIndices, and sum them pairwise. In order to do that, you have to convert them to tuples. So

julia> using Primes

julia> A = [1 2 3; 4 5 6; 7 8 9]
3×3 Array{Int64,2}:
 1  2  3
 4  5  6
 7  8  9

julia> CartesianIndices(A)
3×3 CartesianIndices{2,Tuple{Base.OneTo{Int64},Base.OneTo{Int64}}}:
 CartesianIndex(1, 1)  CartesianIndex(1, 2)  CartesianIndex(1, 3)
 CartesianIndex(2, 1)  CartesianIndex(2, 2)  CartesianIndex(2, 3)
 CartesianIndex(3, 1)  CartesianIndex(3, 2)  CartesianIndex(3, 3)

julia> Tuple.(CartesianIndices(A))
3×3 Array{Tuple{Int64,Int64},2}:
 (1, 1)  (1, 2)  (1, 3)
 (2, 1)  (2, 2)  (2, 3)
 (3, 1)  (3, 2)  (3, 3)

julia> sum.(Tuple.(CartesianIndices(A)))
3×3 Array{Int64,2}:
 2  3  4
 3  4  5
 4  5  6

julia> isprime.(sum.(Tuple.(CartesianIndices(A))))
3×3 BitArray{2}:
 1  1  0
 1  0  1
 0  1  0

This last bitarray can be used for logical indexing. So we make a few alternatives:

foo(A) = A[isprime.(sum.(Tuple.(CartesianIndices(A))))]
bar(A) = A[findall(isprime∘sum∘Tuple, CartesianIndices(A))]
baz(A) = [A[i] for i in CartesianIndices(A) if isprime(sum(Tuple(i)))]

In my tests, foo is the fastest, followed closely by baz, while bar is by far the slowest.

Some may find this more readable:

A[CartesianIndices(A) .|> Tuple .|> sum .|> isprime]

or

A |> CartesianIndices .|> Tuple .|> sum .|> isprime |> (x->A[x])
5 Likes

thank you very much