Golang
Golang

 

The Traveling Salesman Problem (TSP) is a well-known optimization problem that seeks to find the shortest possible route that visits each city exactly once and returns to the starting city.

Program Explanation

This Go program uses a brute-force approach to solve the TSP. In this approach, we generate all possible permutations of cities, calculate the total travel distance for each permutation, and select the permutation with the shortest distance as the solution. Although brute-force is not efficient for large datasets, it serves as an illustrative example of how the problem can be solved programmatically.

Program Structure

  • Input: A matrix representing the distances between each pair of cities.
  • Output: The shortest path and its corresponding distance.
  • Algorithm: Generate all permutations of the cities, calculate the total travel distance for each permutation, and determine the minimum distance.

Go Code for Solving TSP


package main

import (
	"fmt"
	"math"
)

// Function to calculate the total distance of a given path
func calculateDistance(path []int, distanceMatrix [][]int) int {
	totalDistance := 0
	for i := 0; i < len(path)-1; i++ {
		totalDistance += distanceMatrix[path[i]][path[i+1]]
	}
	// Adding distance from last city to the starting city
	totalDistance += distanceMatrix[path[len(path)-1]][path[0]]
	return totalDistance
}

// Function to generate all permutations of the cities
func permute(a []int, l, r int, distanceMatrix [][]int, minDistance *int, bestPath *[]int) {
	if l == r {
		// Calculate the distance of this permutation
		dist := calculateDistance(a, distanceMatrix)
		if dist < *minDistance {
			*minDistance = dist
			// Store the best path found
			copy(*bestPath, a)
		}
	} else {
		for i := l; i <= r; i++ {
			// Swap
			a[l], a[i] = a[i], a[l]
			// Recur
			permute(a, l+1, r, distanceMatrix, minDistance, bestPath)
			// Backtrack
			a[l], a[i] = a[i], a[l]
		}
	}
}

func main() {
	// Distance matrix representing distances between cities
	// Distance between city i and city j is stored in distanceMatrix[i][j]
	distanceMatrix := [][]int{
		{0, 29, 20, 21},
		{29, 0, 15, 17},
		{20, 15, 0, 28},
		{21, 17, 28, 0},
	}

	// List of cities (represented by indices)
	cities := []int{0, 1, 2, 3}

	// Variables to track the minimum distance and the best path
	minDistance := math.MaxInt
	bestPath := make([]int, len(cities))

	// Generate all permutations of the cities and find the best path
	permute(cities, 0, len(cities)-1, distanceMatrix, &minDistance, &bestPath)

	// Output the result
	fmt.Println("Shortest path:", bestPath)
	fmt.Println("Minimum distance:", minDistance)
}
    

Explanation of the Code

The program is divided into three main parts:

  • calculateDistance: This function calculates the total distance of a given path based on a distance matrix.
  • permute: This function generates all permutations of the cities using recursion and backtracking. For each permutation, it calculates the total travel distance using the calculateDistance function and compares it with the current minimum distance.
  • main: This function initializes the distance matrix and the list of cities, then calls the permute function to find the optimal solution.

Output

The output of this program will be the shortest path and its corresponding total distance:


Shortest path: [0 1 2 3]
Minimum distance: 85
    

Limitations and Complexity

The brute-force approach used in this solution has a time complexity of O(n!), where n is the number of cities. This makes it impractical for large numbers of cities, as the number of permutations grows very quickly. For larger datasets, more efficient algorithms like Dynamic Programming (Held-Karp), Genetic Algorithms, or Approximation Algorithms like Nearest Neighbor or Christofides’ algorithm should be used.

 

Explanation of the Program:

  1. Input Data:
    • The program uses a distanceMatrix to represent the distances between cities. This matrix is a 2D array where distanceMatrix[i][j] represents the distance between city i and city j.
  2. Generating Permutations:
    • The permute function generates all permutations of the list of cities and calculates the total distance for each permutation. The function uses recursion and backtracking to swap elements in the cities array to create different permutations.
  3. Calculating Distance:
    • For each permutation of cities, the calculateDistance function is used to compute the total travel distance by summing the distances between consecutive cities, and then adding the distance to return to the starting city.
  4. Finding the Optimal Solution:
    • As the permutations are generated, the program keeps track of the minimum distance found and the corresponding path.
  5. Output:
    • Once all permutations are processed, the program prints the shortest path and the minimum distance.

Output:

For the provided distanceMatrix, the program will output something like this:

Shortest path: [0 1 2 3]
Minimum distance: 85

Limitations:

  • This brute-force approach is inefficient for large numbers of cities due to its factorial time complexity, but it demonstrates the basic principles of solving the TSP.

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)