-3

Given a set of I={0,1,2,3,4}, my code produces feasible optimal routes and the results are look like below: x[0,2]=1, x[2,4]=1, x[4,3]=1 (meaning go from node 0 to node 2 then from 2 to 4, then from 4 to 3) and remaining x[i,j]=0 ( x[0,1]=0 ,x[0,3]=0 , x[2,3]=0,...).

What I need is a single list like this: FinalRoute=[0,2,4,3] which shows the same concept in a single list.

I tried to append those X where x[i,j]=1 to FinalRoute but I can't figure out the order of visited nodes. Is there any way to create a single list (FinalRoute) by appending x[i,j]s in visited order?

MASOUD
  • 41
  • 1
  • 6
  • I think I can't explain the problem clearly! I want a list like [0,2,4,3] (means visit nodes 0,2,4 and 3 in order) GIVEN that I have following lists in hand: x[0,1]=0 , **x[0,2]=1**, x[0,3]=0 , x[0,4]=0 , x[1,2]=0, x[1,3]=0 and x[1,4]=0 , x[2,1]=0 ,x[2,3]=0 , **x[2,4]=1** , x[3,1]=0 , x[3,2]=0, x[3,4]=0 . x[4,1]=0 , x[4,2]=0 ,**x[4,3]=1** – MASOUD May 29 '17 at 10:51
  • It means, wherever x[i,j]=1 then add i and j to single list (but preserve the order of visit!) – MASOUD May 29 '17 at 10:52

1 Answers1

0

Not sure what x[0, 2] is in python, but assuming you have a 2-dimensional list, where you reference values as x[0][2], not x[0, 2] and x[0][2] == 1 means that you go from node0 to node2, here is a possible solution:

matrix = [[0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 1], [0, 0, 0, 0, 0], [0, 0, 0, 1, 0]]

path = []
node = 0
while node is not None:
    path.append(node)
    node = matrix[node].index(1) if 1 in matrix[node] else None

print(path)
Joe Samanek
  • 1,644
  • 12
  • 16
  • Thank you Joe. It seems a wise way of doing this; however, you created matrix by observation (most probably). How can I automate creating a list like matrix? – MASOUD May 29 '17 at 11:06
  • 1
    I don't understand what you are asking. My matrix is just an example, I assume your code produces something like that and then your problem is how to go through the matrix to get the path, which I gave you answer for. If that is not what you needed, then specify what you need more exactly, ideally on an example. – Joe Samanek May 29 '17 at 11:09