Ejemplo n.º 1
0
def NearestNeighbour(locations):
    start_time = time.time()
    shortDistance = 100000
    path = []
    counter = 0
    for x in locations:
        counter += 1
        if counter % 10 == 0:
            print("%.2f%% complete" % (counter / len(locations) * 100),
                  end='\r')
        tempPath = []
        tempLocations = copy.deepcopy(locations)
        currentLocation = x
        tempLocations.remove(currentLocation)
        tempPath.append(x)
        totalDistance = 0

        while tempLocations:
            tempNearestNeighbour = currentLocation
            tempShortestDistance = 10000

            for x in tempLocations:
                if ListFunctions.Distance(
                        x, currentLocation
                ) < tempShortestDistance and ListFunctions.Distance(
                        x, currentLocation) != 0:
                    tempShortestDistance = ListFunctions.Distance(
                        x, currentLocation)
                    tempNearestNeighbour = x
            currentLocation = tempNearestNeighbour
            tempLocations.remove(currentLocation)
            tempPath.append(currentLocation)
            totalDistance += tempShortestDistance

            if len(tempLocations) == 0:
                tempPath.append(tempPath[0])
                totalDistance += ListFunctions.Distance(
                    tempPath[len(tempPath) - 1], tempPath[len(tempPath) - 2])

        if totalDistance < shortDistance:
            shortDistance = totalDistance
            path = tempPath

    print("the total distance is ", shortDistance, " path is ", path)
    print("This process took %.4f seconds to complete" %
          int(time.time() - start_time))

    V.DisplayRoute(path)