Skip to content

Instantly share code, notes, and snippets.

@urfolomeus
Created February 15, 2014 00:00
Show Gist options
  • Save urfolomeus/9012128 to your computer and use it in GitHub Desktop.
Save urfolomeus/9012128 to your computer and use it in GitHub Desktop.
defmodule TspSolver.Fitness do
import TspSolver.Helpers
@city_distances HashDict.new(
[
{ {:Aberdeen, :Dundee}, 67 },
{ {:Aberdeen, :Edinburgh}, 129 },
{ {:Aberdeen, :Glasgow}, 146 },
{ {:Aberdeen, :Inverness}, 105 },
{ {:Aberdeen, :Perth}, 84 },
{ {:Dundee, :Edinburgh}, 63 },
{ {:Dundee, :Glasgow}, 83 },
{ {:Dundee, :Inverness}, 138 },
{ {:Dundee, :Perth}, 22 },
{ {:Edinburgh, :Glasgow}, 43 },
{ {:Edinburgh, :Inverness}, 154 },
{ {:Edinburgh, :Perth}, 45 },
{ {:Glasgow, :Inverness}, 175 },
{ {:Glasgow, :Perth}, 62 },
{ {:Inverness, :Perth}, 117 }
]
)
def of_individual(individual) do
Enum.reduce individual, 0, fn (city, distance) ->
next_city_index = index_of(individual, city) + 1
next_city = next_city(individual, next_city_index)
distance + _distance_between(city, next_city)
end
end
defp next_city(cities, index) when index < Kernel.length(cities) do
Enum.at(cities, index)
end
defp next_city(cities, _), do: List.first(cities)
defp _distance_between(city, next_city) do
HashDict.get @city_distances, cities(city, next_city)
end
defp cities(city, next_city) do
[city, next_city] |> Enum.sort |> Kernel.list_to_tuple
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment