I’m implementing a genetic algorithm (GA) to solve the Traveling Salesman Problem (TSP), and I need help defining a fitness function for it.
Here is my solution to calculate the distance of a given path and then evaluate the fitness (where the fitness is the inverse of the distance — shorter paths are more fit):
# Function to calculate the distance of a path
def distance(path, dist_matrix):
return sum(dist_matrix[path[i]][path[i+1]] for i in range(len(path)-1)) + dist_matrix[path[-1]][path[0]]
# Fitness function: inverse of distance (shorter paths are better)
def fitness(path, dist_matrix):
return 1 / distance(path, dist_matrix)
# Distance matrix (example for a 4-city problem)
dist_matrix = [
[0, 2, 9, 10],
[1, 0, 6, 4],
[15, 7, 0, 8],
[6, 3, 12, 0]
]
# Example path (city visit order)
path = [0, 1, 3, 2]
# Print the distance and fitness of the example path
print("Distance:", distance(path, dist_matrix))
print("Fitness:", fitness(path, dist_matrix))