Multi-dimensional array of tuples

I am working in an combinatorial optimization problem (multiple vehicle routing with profits) where I have a binary variable x[i,j,p] representing an edge (i,j) traversed by a vehicle p. I would like to get a p-dimensional array of tuples (i,j) regarding each path ā€˜pā€™ when value.(x[i,j,p])=1 . I am using JuMP package.
To a better understanding: 1:n is the set of nodes and L is a subset of 1:n
I am trying this block of code inside another loop because I am reoptimizing sevral times:

g1 = Tuple{Int,Int}[]
    g2 = Tuple{Int,Int}[]
    for p in 1:P
        if p == 1
            append!(g1, (i,j) for i in 1:n, j in 1:n if (i in L || j in L) && (value.(x[i, j, p]) >= a) && (i!=1 && j!=n))
        else
            append!(g2, (i,j) for i in 1:n, j in 1:n if (i in L || j in L) && (value.(x[i, j, p]) >= a) && (i!=1 && j!=n))
        end
    end

And I get, for example:

g1 = [(7, 11), (11, 16), (16, 22)]
g2 = [(8, 12), (12, 17)]

However, I would like to have something like this, if p=2 :

g = [[(7, 11), (11, 16), (16, 22)], [(8, 12), (12, 17)]]

and a more general and efficient code taking accounting different values of p . I would appreciate if someone could help me with this.

Welcome. A good start is often write things as a functions:

tuple_match(n,L,x,a,p) = [(i,j) for i in 2:n, j in 1:(n-1) if (i in L || j in L) && (value(x[i, j, p]) >= a)]

or a more general version would be

tuple_match(S1,S2,L,x,a,p) = [(i,j) for i in S1, j in S2 if (i in L || j in L) && (value(x[i, j, p]) >= a)]

where S1 = 2:n and S2 = 1:(n-1) etc. in your code.

Here Iā€™m using Comprehensions.

Then you could write, for given values of n, L, x, a ,

g = [tuple_match(n, L, x, a, p) for p in 1:P]
1 Like

Thank you so much, @jd-foster! It worked perfectly!

1 Like