|
| 1 | +""" |
| 2 | +Small library for complex numbers |
| 3 | +""" |
| 4 | + |
| 5 | + |
| 6 | +# Cardinal directions |
| 7 | +north = 1j |
| 8 | +south = -1j |
| 9 | +west = -1 |
| 10 | +east = 1 |
| 11 | +northeast = 1 + 1j |
| 12 | +northwest = -1 + 1j |
| 13 | +southeast = 1 - 1j |
| 14 | +southwest = -1 - 1j |
| 15 | + |
| 16 | +directions_straight = [north, south, west, east] |
| 17 | +directions_diagonals = directions_straight + [ |
| 18 | + northeast, |
| 19 | + northwest, |
| 20 | + southeast, |
| 21 | + southwest, |
| 22 | +] |
| 23 | + |
| 24 | +# To be multiplied by the current cartinal direction |
| 25 | +relative_directions = { |
| 26 | + "left": 1j, |
| 27 | + "right": -1j, |
| 28 | + "ahead": 1, |
| 29 | + "back": -1, |
| 30 | +} |
| 31 | + |
| 32 | + |
| 33 | +def min_real(complexes): |
| 34 | + real_values = [x.real for x in complexes] |
| 35 | + return min(real_values) |
| 36 | + |
| 37 | + |
| 38 | +def min_imag(complexes): |
| 39 | + real_values = [x.imag for x in complexes] |
| 40 | + return min(real_values) |
| 41 | + |
| 42 | + |
| 43 | +def max_real(complexes): |
| 44 | + real_values = [x.real for x in complexes] |
| 45 | + return max(real_values) |
| 46 | + |
| 47 | + |
| 48 | +def max_imag(complexes): |
| 49 | + real_values = [x.imag for x in complexes] |
| 50 | + return max(real_values) |
| 51 | + |
| 52 | + |
| 53 | +def manhattan_distance(a, b): |
| 54 | + return abs(b.imag - a.imag) + abs(b.real - a.real) |
| 55 | + |
| 56 | + |
| 57 | +def complex_sort(complexes, mode=""): |
| 58 | + # Sorts by real, then by imaginary component (x then y) |
| 59 | + if mode == "xy": |
| 60 | + complexes.sort(key=lambda a: (a.real, a.imag)) |
| 61 | + # Sorts by imaginary, then by real component (y then x) |
| 62 | + elif mode == "yx": |
| 63 | + complexes.sort(key=lambda a: (a.imag, a.real)) |
| 64 | + # Sorts by distance from 0,0 (kind of polar coordinates) |
| 65 | + else: |
| 66 | + complexes.sort(key=lambda a: sqrt(a.imag ** 2 + a.real ** 2)) |
| 67 | + return complexes |
0 commit comments