-
Notifications
You must be signed in to change notification settings - Fork 0
/
coord.py
107 lines (91 loc) · 3 KB
/
coord.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import math
from typing import Union
class Coord:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def __eq__(self, other):
if isinstance(other, Coord):
if self.x != other.x or self.y != other.y:
return False
else:
return False
return True
def __hash__(self):
prime = 31
result = 1
result = prime * result + self.x
result = prime * result + self.y
return result
def __str__(self):
return f'({self.x} {self.y})'
def __repr__(self):
return self.__str__()
def manhattan_to(self, other: Union[tuple, 'Coord']) -> int:
if isinstance(other, Coord):
x, y = other.x, other.y
elif isinstance(other, tuple) and len(other) == 2:
x, y = other
else:
raise ValueError
return abs(self.x - x) + abs(self.y - y)
def chebyshev_to(self, other: Union[tuple, 'Coord']):
if isinstance(other, Coord):
x, y = other.x, other.y
elif isinstance(other, tuple) and len(other) == 2:
x, y = other
else:
raise ValueError
return max(abs(self.x - x), abs(self.y - y))
def get_unit_vector(self) -> 'Coord':
x = 0 if self.x == 0 else self.x // abs(self.x)
y = 0 if self.y == 0 else self.y // abs(self.y)
return Coord(x, y)
def get(self):
return self.x, self.y
def __add__(self, other):
if isinstance(other, Coord):
x, y = other.x, other.y
elif isinstance(other, tuple) and len(other) == 2:
x, y = other
elif isinstance(other, int):
x, y = other, other
else:
raise ValueError
return Coord(self.x + x, self.y + y)
def __radd__(self, other):
if isinstance(other, (int, tuple, Coord)):
self.__add__(other)
else:
raise ValueError
def __sub__(self, other):
if isinstance(other, Coord):
x, y = other.x, other.y
elif isinstance(other, tuple) and len(other) == 2:
x, y = other
elif isinstance(other, int):
x, y = other, other
else:
raise ValueError
return Coord(self.x - x, self.y - y)
def __mul__(self, other):
if isinstance(other, Coord):
x, y = other.x, other.y
elif isinstance(other, tuple) and len(other) == 2:
x, y = other
elif isinstance(other, int):
x, y = other, other
else:
raise ValueError
return Coord(self.x * x, self.y * y)
def __rmul__(self, other):
if isinstance(other, (int, tuple, Coord)):
self.__mul__(other)
else:
raise ValueError
@staticmethod
def adjacency(eight=False):
adj = [Coord(0, -1), Coord(1, 0), Coord(0, 1), Coord(-1, 0)]
if eight:
adj += [Coord(1, 1), Coord(1, -1), Coord(-1, -1), Coord(-1, 1)]
return adj