Skip to content
Snippets Groups Projects
Commit fe353383 authored by tobiglaser's avatar tobiglaser
Browse files

Initial commit

parents
No related branches found
No related tags found
No related merge requests found
import matplotlib.pyplot as plt
from math import *
from random import randint
from string import ascii_uppercase
from itertools import permutations
# config:
brute_force = True
num_nodes = 9
do_plot = True
pause = 1
class Node:
x: int
y: int
name: str
def __init__(self, x: int, y: int, name: str):
self.x = x
self.y = y
self.name = name
def plot(this):
plt.plot(this.x, this.y, 'ro', label=this.name)
def distance(A: Node, B: Node) -> float:
return sqrt((A.x - B.x)**2 + (A.y - B.y)**2)
def total_distance(route: list) -> float:
total_distance = 0
for i in range(len(route)):
if i == len(route)-1:
total_distance += distance(route[i], route[0])
else:
total_distance += distance(route[i], route[i+1])
return total_distance
class Path:
A: Node
B: Node
distance: float
def __init__(self, A: Node, B: Node):
self.A = A
self.B = B
#self.distance = distance(A, B)
def plot(this):
plt.plot([this.A.x, this.B.x], [this.A.y, this.B.y], 'go-')
def plot_route(route: list) -> None:
plt.close("all")
for i in range(len(route)):
if i == len(route) - 1:
Path(A=route[i], B=route[0]).plot()
else:
Path(A=route[i], B=route[i+1]).plot()
plt.show()
plt.pause(pause)
def brute(nodes: list):
if len(nodes) <= 1:
return
best_route = nodes
best_route_length = total_distance(nodes)
if do_plot:
plot_route(best_route)
for i, route in enumerate(permutations(nodes, len(nodes))):
route_length = total_distance(route)
if route_length < best_route_length:
best_route = route
best_route_length = route_length
print("Found shorter Route with length " + str(best_route_length) + " after " + str(i) + " iterations.")
if do_plot:
plot_route(best_route)
print(str(i+1) + " iterations in total")
return best_route
def generate_paths(nodes: list) -> list:
_nodes = nodes.copy()
paths = []
if _nodes.__len__() <= 1:
return []
this_node = _nodes[0]
_nodes.remove(_nodes[0])
for node in _nodes:
paths.append(Path(A=this_node, B=node))
if _nodes.__len__() >= 2:
paths = paths + generate_paths(_nodes)
return paths
if __name__ == "__main__":
nodes = []
for i in range(num_nodes):
nodes.append(Node(x=randint(0, 100), y=randint(0, 100), name=ascii_uppercase[i]))
plt.ion()
best_route = brute(nodes)
plot_route(best_route)
plt.show(block=True)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment