commit local changes.
This commit is contained in:
+48
-14
@@ -23,10 +23,10 @@ def get_distance_point(p1, p2):
|
||||
|
||||
return wurzel(dx**2 + dy**2)
|
||||
|
||||
def get_distance_points(p):
|
||||
def get_distance_points(ps):
|
||||
distance = 0
|
||||
for i in range(len(p) - 1):
|
||||
distance += get_distance_point(p[i], p[i + 1])
|
||||
for i in range(len(ps) - 1):
|
||||
distance += get_distance_point(ps[i], ps[i + 1])
|
||||
return distance
|
||||
|
||||
def add_point(x=None, y=None):
|
||||
@@ -58,28 +58,62 @@ def bruteforce():
|
||||
print(f"Possible ways: {max_ways}")
|
||||
time.sleep(2)
|
||||
ways = []
|
||||
for i in range(max_ways):
|
||||
new_way = []
|
||||
while len(new_way) < len(points):
|
||||
n = random.choice(points)
|
||||
if n not in new_way:
|
||||
new_way.append(n)
|
||||
distance = get_distance_points(new_way)
|
||||
if mode == "verbose":
|
||||
print(f"\r{i + 1}: {new_way}, distance: {distance}", end="")
|
||||
ways.append({"way": new_way, "distance": distance})
|
||||
while len(ways) < max_ways:
|
||||
new_way_dict = get_way()
|
||||
if new_way_dict not in ways:
|
||||
ways.append(new_way_dict)
|
||||
if mode == "verbose":
|
||||
print(f"\r {new_way_dict}")
|
||||
print(f"\rWays: {len(ways)}/{max_ways}", end="")
|
||||
return ways
|
||||
|
||||
def get_way():
|
||||
new_way = []
|
||||
while len(new_way) < len(points):
|
||||
n = random.choice(points)
|
||||
if n not in new_way:
|
||||
new_way.append(n)
|
||||
distance = get_distance_points(new_way)
|
||||
return {"way": new_way, "distance": distance}
|
||||
|
||||
def smartforce(limit):
|
||||
way_dict = get_way()
|
||||
start = time.monotonic()
|
||||
while start + limit > time.monotonic():
|
||||
if mode == "verbose":
|
||||
print(f"\rWay: {way_dict['way']}, distance: {way_dict['distance']}", end="")
|
||||
time.sleep(2)
|
||||
route = way_dict['way']
|
||||
i = random.randrange(len(route))
|
||||
j = random.randrange(len(route))
|
||||
|
||||
route[i], route[j] = route[j], route[i]
|
||||
new_distance = get_distance_points(route)
|
||||
if new_distance < way_dict['distance']:
|
||||
way_dict = {"way": route, "distance": new_distance}
|
||||
else:
|
||||
route[i], route[j] = route[j], route[i]
|
||||
return way_dict
|
||||
|
||||
|
||||
def start():
|
||||
print("TSM algorithm")
|
||||
print("\nBRUTEFORCE\n")
|
||||
start = time.monotonic()
|
||||
ways = bruteforce()
|
||||
end = time.monotonic()
|
||||
print(f"Took: {end - start}")
|
||||
print(f"Took: {(end - start)/60}Min")
|
||||
distances = []
|
||||
for i in range(len(ways)):
|
||||
distances.append(ways[i]["distance"])
|
||||
print(f"Fastest: {min(distances)}, slowest: {max(distances)}")
|
||||
print("\n")
|
||||
time.sleep(2)
|
||||
limit = float(input("Enter limit for smartforce: "))
|
||||
way = smartforce(limit)
|
||||
print(f"Smartforce: {way}")
|
||||
print("\n")
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user