79590820

Date: 2025-04-24 14:19:46
Score: 3
Natty:
Report link

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))
Reasons:
  • Blacklisted phrase (0.5): I need
  • Blacklisted phrase (2.5): I need help
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Prito