summaryrefslogtreecommitdiffstats
path: root/03-travelling-salesman/solver.py
diff options
context:
space:
mode:
Diffstat (limited to '03-travelling-salesman/solver.py')
-rw-r--r--03-travelling-salesman/solver.py50
1 files changed, 50 insertions, 0 deletions
diff --git a/03-travelling-salesman/solver.py b/03-travelling-salesman/solver.py
new file mode 100644
index 0000000..8e29526
--- /dev/null
+++ b/03-travelling-salesman/solver.py
@@ -0,0 +1,50 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+import math
+
+def length(point1, point2):
+ return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)
+
+def solveIt(inputData):
+ # Modify this code to run your optimization algorithm
+
+ # parse the input
+ lines = inputData.split('\n')
+
+ nodeCount = int(lines[0])
+
+ points = []
+ for i in range(1, nodeCount+1):
+ line = lines[i]
+ parts = line.split()
+ points.append((float(parts[0]), float(parts[1])))
+
+ # build a trivial solution
+ # visit the nodes in the order they appear in the file
+ solution = range(0, nodeCount)
+
+ # calculate the length of the tour
+ obj = length(points[solution[-1]], points[solution[0]])
+ for index in range(0, nodeCount-1):
+ obj += length(points[solution[index]], points[solution[index+1]])
+
+ # prepare the solution in the specified output format
+ outputData = str(obj) + ' ' + str(0) + '\n'
+ outputData += ' '.join(map(str, solution))
+
+ return outputData
+
+
+import sys
+
+if __name__ == '__main__':
+ if len(sys.argv) > 1:
+ fileLocation = sys.argv[1].strip()
+ inputDataFile = open(fileLocation, 'r')
+ inputData = ''.join(inputDataFile.readlines())
+ inputDataFile.close()
+ print solveIt(inputData)
+ else:
+ print 'This test requires an input file. Please select one from the data directory. (i.e. python solver.py ./data/tsp_51_1)'
+