How to find pairs of indices that meet specific criteria

Hi all,

Let E be an array such that E = [3,5,3,5,3] so E[1] = 3,…,E[5] = 3.
I want to find and collect the pairs of two indices such that (E[1],E[2]), (E[1],E[4]),(E[2],E[4]), (E[2],E[5]), (E[3],E[4]), (E[4], E[5]). That is, the couples (i,j) such that i < j and E[i]≠E[j].

Is there a way to obtain it? Thanks in advance.

Yes.

julia> [(i, j) for i = eachindex(E) for j = i:lastindex(E) if E[i] != E[j]]
6-element Array{Tuple{Int64,Int64},1}:
 (1, 2)
 (1, 4)
 (2, 3)
 (2, 5)
 (3, 4)
 (4, 5)
2 Likes

thanks a lot! This works for me.

I think that, maybe, the most generic solution is this one:

julia> [(i, j) for i = eachindex(E) for j = Iterators.rest(E, i) if E[i] != j]
6-element Array{Tuple{Int64,Int64},1}:
 (2, 5)
 (2, 3)
 (2, 5)
 (2, 3)
 (4, 5)
 (4, 3)

Note that both solutions I gave start with j with the same value as E[i] but this is not a problem because E[i] != E[i] is never true (in a sane code).

EDIT NOTE: this code was simply wrong before, as I thought Iterators.rest returned indexes, not values.

1 Like