Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • glasert/angewandtemathe
1 result
Show changes
Commits on Source (2)
*.svg
\ No newline at end of file
import numpy as np import numpy as np
from copy import deepcopy from copy import deepcopy
import chess
import chess.svg
from IPython.display import Image
from IPython.display import SVG
class Board: class Board:
blocked = 0 blocked = 0
...@@ -71,10 +74,36 @@ class Board: ...@@ -71,10 +74,36 @@ class Board:
return True return True
else: else:
return False return False
def display_chess_board(self) -> None:
string = ""
for row in range(self.dimY):
spaces = 0
for column in range(self.dimX):
if self.board[column, row] == self.queen:
if spaces > 0:
string += str(spaces)
string += "q"
spaces = 0
else:
spaces += 1
if spaces > 0:
string += str(spaces)
if row < self.dimY-1:
string += "/"
board = chess.Board(string)
boardsvg = chess.svg.board(board, size=350)
outputfile = open('temp.svg', "w")
outputfile.write(boardsvg)
outputfile.close()
display(SVG("temp.svg"))
if __name__ == "__main__": if __name__ == "__main__":
board = Board(8, 8) board = Board(8, 8)
num_queens = 8
solutions = []
saved_boards = [] saved_boards = []
iters = 0 iters = 0
...@@ -85,3 +114,15 @@ if __name__ == "__main__": ...@@ -85,3 +114,15 @@ if __name__ == "__main__":
board.toConsole() board.toConsole()
saved_boards.append(board.copy()) saved_boards.append(board.copy())
print("Queens: " + str(iters)) print("Queens: " + str(iters))
board.display_chess_board()
def recurse(board: Board, branch: int, depth: int) -> None:
# Anker:
oldBoard = board
workboard = board.copy()
# traversiere links
\ No newline at end of file
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from math import * from math import sqrt
from random import randint from random import randint
from string import ascii_uppercase
from itertools import permutations from itertools import permutations
# config: # config:
brute_force = False ## use tsp01.data?
optimize = True from_file = False
## number of nodes when false:
num_nodes = 10 num_nodes = 10
do_plot = False ## brute force or nearest neighbout?
pause = 1 brute_force = True
## apply 2-opt?
optimize = False
## plot better routes during calcutation
do_plot = True
## duration of pause between plots (for better visibility)
pause = 0
class Node: class Node:
x: int x: int
...@@ -21,39 +28,37 @@ class Node: ...@@ -21,39 +28,37 @@ class Node:
def plot(this): def plot(this):
plt.plot(this.x, this.y, 'ro', label=this.name) plt.plot(this.x, this.y, 'ro', label=this.name)
def __str__(self) -> str:
if self.name != "":
return "x: " + str(self.x) + "\ty: " + str(self.y) + "\tname: " + self.name
else:
return "x: " + str(self.x) + "\ty: " + str(self.y)
def distance(A: Node, B: Node) -> float: def distance(A: Node, B: Node) -> float:
return sqrt((A.x - B.x)**2 + (A.y - B.y)**2) return sqrt((A.x - B.x)**2 + (A.y - B.y)**2)
def total_distance(route: list) -> float: def total_distance(route: list, circle: bool = False) -> float:
total_distance = 0 total_distance = 0
for i in range(len(route)): for i in range(len(route)):
if i == len(route)-1: if i == len(route)-1:
total_distance += distance(route[i], route[0]) if circle:
total_distance += distance(route[i], route[0])
else: else:
total_distance += distance(route[i], route[i+1]) total_distance += distance(route[i], route[i+1])
return total_distance return total_distance
class Path: def plot_path(A: Node, B: Node):
A: Node plt.plot([A.x, B.x], [A.y, B.y], 'go-')
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, nodes: list = [], circle: bool = False) -> None: def plot_route(route: list, nodes: list = [], circle: bool = False) -> None:
plt.close("all") plt.close("all")
for i in range(len(route)): for i in range(len(route)):
if i == len(route) - 1 and circle: if i == len(route) - 1:
Path(A=route[i], B=route[0]).plot() if circle:
plot_path(A=route[i], B=route[0])
else: else:
Path(A=route[i], B=route[i+1]).plot() plot_path(A=route[i], B=route[i+1])
for node in nodes: for node in nodes:
node.plot() node.plot()
plt.show() plt.show()
...@@ -64,18 +69,17 @@ def brute(nodes: list) -> list: ...@@ -64,18 +69,17 @@ def brute(nodes: list) -> list:
if len(nodes) <= 1: if len(nodes) <= 1:
return return
best_route = nodes best_route = nodes
best_route_length = total_distance(nodes) best_route_length = total_distance(nodes, circle=True)
if do_plot: if do_plot:
plot_route(best_route) plot_route(best_route, circle=True)
#TODO Noch nicht rekursiv!
for i, route in enumerate(permutations(nodes, len(nodes))): for i, route in enumerate(permutations(nodes, len(nodes))):
route_length = total_distance(route) route_length = total_distance(route, circle=True)
if route_length < best_route_length: if route_length < best_route_length:
best_route = route best_route = route
best_route_length = route_length best_route_length = route_length
print("Found shorter Route with length " + str(best_route_length) + " after " + str(i) + " iterations.") print("Found shorter Route with length " + str(best_route_length) + " after " + str(i) + " iterations.")
if do_plot: if do_plot:
plot_route(best_route) plot_route(best_route, circle=True)
print(str(i+1) + " iterations in total") print(str(i+1) + " iterations in total")
return best_route return best_route
...@@ -110,29 +114,13 @@ def nearest_neighbour(_nodes: list) -> list: ...@@ -110,29 +114,13 @@ def nearest_neighbour(_nodes: list) -> list:
return route return 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
#TODO Zuweisungen brechen die Kette! #TODO Zuweisungen brechen die Kette!
def optimize_2opt(_route: list) -> list: def optimize_2opt(_route: list) -> list:
route = _route.copy() route = _route.copy()
for i in range(len(route)-1): for i in range(len(route)-1):
print("My 2-opt is broken!")
print("TODO Zuweisungen brechen die Kette!")
a = route[i] a = route[i]
b = route[i+1] b = route[i+1]
ab = distance(a, b) ab = distance(a, b)
...@@ -175,17 +163,24 @@ def optimize_2opt(_route: list) -> list: ...@@ -175,17 +163,24 @@ def optimize_2opt(_route: list) -> list:
swapped = True swapped = True
if swapped: if swapped:
break break
return route return route
def parse_data_file(path: str) -> list:
nodes = []
with open(file=path, mode='r') as file:
for line in file:
coordinates = line.split('\t')
new_node = Node(x=float(coordinates[0]), y=float(coordinates[1]))
nodes.append(new_node)
return nodes
if __name__ == "__main__": if __name__ == "__main__":
nodes = [] nodes = []
for i in range(num_nodes): if from_file:
nodes.append(Node(x=randint(0, 100), y=randint(0, 100), name=str(hex(i)))) nodes = parse_data_file("tsp01.data")
else:
for i in range(num_nodes):
nodes.append(Node(x=randint(0, 100), y=randint(0, 100), name=str(hex(i))))
plt.ion() plt.ion()
......
8.00 124.0
125.0 80.0
97.0 74.0
69.0 96.0
106.0 46.0
49.0 57.0
80.0 125.0
42.0 93.0
104.0 94.0
35.0 17.0
118.0 96.0
151.0 22.0
154.0 182.0
57.0 165.0
18.0 159.0
\ No newline at end of file