From: Skullheadx <94652084+Skullheadx@users.noreply.github.com> Date: Tue, 27 Dec 2022 04:47:42 +0000 (-0500) Subject: brute force demo X-Git-Url: http://git.skullheadx.com/links.html?a=commitdiff_plain;h=d6d868378bcde23b847f1095b5cc99bab3316102;p=The-Traveling-Salesman-Problem.git brute force demo --- diff --git a/brute_force.py b/brute_force.py new file mode 100644 index 0000000..6800e3c --- /dev/null +++ b/brute_force.py @@ -0,0 +1,31 @@ +from queue import Queue +from graph import calculate_distance + + +def brute_force(graph: list) -> list: + routes = [] + q = Queue() + q.put([]) + + while not q.empty(): + current = q.get() + if len(current) == len(graph): + current.append(current[0]) + routes.append(current) + continue + + for node in graph: + if node not in current: + temp = current[:] + temp.append(node) + q.put(temp) + + shortest_distance = None + shortest_route = [] + for route in routes: + distance = calculate_distance(route) + if shortest_distance is None or distance < shortest_distance: + shortest_distance = distance + shortest_route = route + + return shortest_route diff --git a/main.py b/main.py index f504265..a8c1ebe 100644 --- a/main.py +++ b/main.py @@ -1,15 +1,29 @@ from graph import create from display import Display +from brute_force import brute_force import os GRAPH_PATH = "graphs/" +DELETE_PREVIOUS_FILES = True def main(): - graph, filename = create(GRAPH_PATH, 640, 640, 20) + if DELETE_PREVIOUS_FILES: + for root, dirs, files in os.walk("graphs/"): + for name in files: + path = os.path.join(root, name) + + if os.path.exists(path): + os.remove(path) + else: + print("The file does not exist") + + graph, filename = create(GRAPH_PATH, 640, 640, 5) display = Display(os.path.join(GRAPH_PATH, filename)) - display.show(graph) + route = brute_force(graph) + + display.show(route) if __name__ == "__main__":