i’m making a method for my friend’s application, that returns the routes of a vehicle.
for example, Bus1 has routes A-to-B, B-to-C, C-to-D and in the end there remains a pair whose end is alone just like the first pair’s A.
the query is returning the results scrambled since the sequence of routes differs for each vehicle, so i tried to write a method that would sort these combinations to make a path. like a chain. im using chars as locations and strings as routes here.
public void MakePath(ref List<string> routes)
{
for (int i = 0; i < routes.Count - 1; i++)
{
for (int j = 0; j < routes.Count; j++)
{
if (routes[i][1] == routes[j][0])
{
var temp = routes[i + 1];
routes[i + 1] = routes[j];
routes[j] = temp;
j = routes.Count;
}
}
}
}
it works fine in some situations, that is if the last pair is already at its right position.
otherwise it doesn’t work, for example
“CD” “AB” “BC”
doesn’t work with this. i know it doesn’t work because second char of first string is alone as its supposed to be the last pair, so what should i do in this method to take care of the last pair?
You have to first scan the list and find the terminal stations of the route. In its simplest form this is an algorithm quadratic in the size of the route.
After that you can put the terminal segments of the route in their correct places. After that run your algorithm to “iron” the stuff in-between.