Reputation: 31
i am trying to do the equvilant of this in haskell bascially
for (int i = 0; i < city_Permutation_Route.length - 1; i++) {
route_Distance = route_Distance + city_Distance_Matrix[city_Permutation_Route[i]][city_Permutation_Route[i + 1]];
}
there i get the weight of each route, compare it against each of the others so that i print out the route with the lowest weighted route as follows
Route Weight = 453.4 Route = 0,1,2,3,4,5,6,7,8
i have functions to get the total route and all the other data but do not understand how to get values from the matrix
Question: How do i do this in haskell
i want to be able to get the values from my distance matrix using the permutation values as the index to it
Upvotes: 0
Views: 179
Reputation: 24156
Given a permutation, for example [3, 2, 7, 5, 4, 6, 0, 1]
you can compute all of the legs by zip
ping it with its own tail
.
zip [3, 2, 7, 5, 4, 6, 0, 1]
(tail [3, 2, 7, 5, 4, 6, 0, 1])
zip [3, 2, 7, 5, 4, 6, 0, 1]
[2, 7, 5, 4, 6, 0, 1]
[(3,2),(2,7),(7,5),(5,4),(4,6),(6,0),(0,1)]
These are the indexes into the distance matrix for the cost of traveling between two points. If we look these up in the city_Distance_Matrix
using the list indexing function !!
we get the cost for each leg
map (\(c0, c1) -> city_Distance_Matrix !! c0 !! c1)
[(3,2),(2,7),(7,5),(5,4),(4,6),(6,0),(0,1)]
[97.4, 71.6, 111.0,138.0,85.2 ,86.3 ,129.0]
If we total these, we get the total cost for traveling the legs of this permutation.
sum [97.4, 71.6, 111.0,138.0,85.2 ,86.3 ,129.0] = 718.5
Putting this all together, we can define a function that computes the total length of all the legs of a permutation of the cities. We can simplify the function by using zipWith
which is a combination of zip
and map
.
totalLength :: [Int] -> Double
totalLength cities = sum $ zipWith (\c0 c1 -> city_Distance_Matrix !! c0 !! c1) cities (tail cities)
You should be able to use this to find the permutation whose totalLength
is minimal.
Upvotes: 4