0% found this document useful (0 votes)
12 views4 pages

REPORT

The document details an implementation of a heuristic solution to the Two Salesman Problem using the Nearest Neighbor algorithm for tour generation and splitting the tour into two parts. It describes reading input data, calculating distances, generating tours, splitting tours, calculating lengths, and writing output.

Uploaded by

juliejoe122jj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views4 pages

REPORT

The document details an implementation of a heuristic solution to the Two Salesman Problem using the Nearest Neighbor algorithm for tour generation and splitting the tour into two parts. It describes reading input data, calculating distances, generating tours, splitting tours, calculating lengths, and writing output.

Uploaded by

juliejoe122jj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Report: Two Salesman Problem (2-TSP) Solution using Nearest

Neighbor Heuristic

1. Introduction
The Two Salesman Problem (2-TSP) is a variant of the classical Traveling Salesman Problem
(TSP), where the goal is to determine two separate tours for two salesmen such that the total
distance traveled is minimized. This report details the implementation of a heuristic solution to
the 2-TSP using the Nearest Neighbor algorithm for tour generation and a simple tour splitting
strategy.
2. Methodology
The solution to the 2-TSP involves the following key steps:
1. Reading Input: Load city coordinates from a file.
2. Distance Calculation: Compute a distance matrix representing the Euclidean distances
between each pair of cities.
3. Tour Generation: Use the Nearest Neighbor algorithm to generate an initial tour
starting from a randomly chosen city.
4. Tour Splitting: Divide the generated tour into two approximately equal parts for the two
salesmen.
5. Tour Length Calculation: Compute the total length of each tour.
6. Writing Output: Save the results to an output file in a specified format.
3. Implementation Details
3.1 Reading Input

The read_input function reads city coordinates from an input file and stores them in a list of
tuples, where each tuple contains a city ID and its (x, y) coordinates.

def read_input(file_name):
cities = []
with open(file_name, 'r') as f:
for line in f:
city_id, x, y = map(int, line.strip().split())
cities.append((city_id, x, y))
return cities

3.2 Distance Calculation


The calculate_distance function computes the Euclidean distance between two cities. The
create_distance_matrix function creates a symmetric distance matrix using these distances.

def calculate_distance(c1, c2):


return round(math.sqrt((c1[1] - c2[1])**2 + (c1[2] - c2[2])**2))

def create_distance_matrix(cities):
n = len(cities)
dist_matrix = [[0]*n for _ in range(n)]
for i in range(n):
for j in range(i+1, n):
dist = calculate_distance(cities[i], cities[j])
dist_matrix[i][j] = dist
dist_matrix[j][i] = dist
return dist_matrix

3.3 Tour Generation


The nearest_neighbor function generates a tour starting from a given city using the Nearest
Neighbor heuristic. It iteratively selects the nearest unvisited city until all cities are visited.

def nearest_neighbor(dist_matrix, start):


n = len(dist_matrix)
unvisited = set(range(n))
tour = [start]
unvisited.remove(start)
current = start
while unvisited:
next_city = min(unvisited, key=lambda city: dist_matrix[current][city])
tour.append(next_city)
unvisited.remove(next_city)
current = next_city
return tour

3.4 Tour Splitting


The split_tours function divides the generated tour into two approximately equal parts for the
two salesmen.

def split_tours(tour):
half = len(tour) // 2
return tour[:half], tour[half:]

3.5 Tour Length Calculation


The calculate_tour_length function computes the total length of a given tour by summing the
distances between consecutive cities and adding the distance from the last city back to the first
city.

def calculate_tour_length(dist_matrix, tour):


return sum(dist_matrix[tour[i]][tour[i+1]] for i in range(len(tour)-1)) + dist_matrix[tour[-1]]
[tour[0]]
3.6 Writing Output
The write_output function saves the total distance, individual tour lengths, and the sequence of
cities for each tour to an output file in the specified format.

def write_output(file_name, tour1, tour2, dist1, dist2):


with open(file_name, 'w') as f:
f.write(f"{dist1 + dist2}\n")
f.write(f"{dist1} {len(tour1)}\n")
for city in tour1:
f.write(f"{city}\n")
f.write("\n")
f.write(f"{dist2} {len(tour2)}\n")
for city in tour2:
f.write(f"{city}\n")
f.write("\n")

4. Main Function
The main function orchestrates the overall process by invoking the aforementioned functions in
sequence.

def main(input_file, output_file):


# Read the cities and their coordinates from the input file
cities = read_input(input_file)

# Create a distance matrix based on the cities' coordinates


dist_matrix = create_distance_matrix(cities)

# Select a random start city for the initial tour


start_city = random.randint(0, len(cities) - 1)

# Generate a tour using the Nearest Neighbor Algorithm


tour = nearest_neighbor(dist_matrix, start_city)

# Split the tour into two parts for the two salesmen
tour1, tour2 = split_tours(tour)

# Calculate the total length of each tour


dist1 = calculate_tour_length(dist_matrix, tour1)
dist2 = calculate_tour_length(dist_matrix, tour2)

# Write the results to the output file


write_output(output_file, tour1, tour2, dist1, dist2)
# Specify the input and output file names
input_file = 'test-input-4.txt'
output_file = 'test-output-4.txt'

# Call the main function


main(input_file, output_file)

5. Conclusion
This report presents a heuristic solution to the Two Salesman Problem (2-TSP) using the
Nearest Neighbor algorithm for initial tour generation and a simple splitting strategy for
dividing the tour between two salesmen. The implementation efficiently reads city coordinates,
computes a distance matrix, generates tours, splits them, calculates tour lengths, and writes the
results to an output file. This approach provides a practical method for solving the 2-TSP,
suitable for moderate-sized datasets.

You might also like