确定二维数组中两点之间的旋转

问题描述 投票:0回答:2

假设我有一个 4 x 4 的迷宫,如下所示,并且我编写了一个程序,该程序返回从开始到结束的可能路径,如下所示:

[(3, 1), (3, 0), (2, 0), (3, 0), (3, 1), (3, 2), (2, 2), (2, 3), (1, 3), (1, 2), (0, 2), (1, 2), (1, 1), (1, 0), (0, 0), (0, 1)]

起点是第一个元素,终点是最后一个元素。

如何向每个包含以 90 度为增量旋转的元组添加第三个值?如果发生旋转,它应该返回旋转和方向,其中

-
表示逆时针旋转。假设您开始面向北。

例如,对于前两点,

[(3, 1), (3, 0), ... ]

它应该返回,

[(3, 1, -90), (3, 0, 90), ... ]

(3, 1)
一样,您必须转向朝西才能移动到下一个点,而在
(3, 0)
上,您必须转向朝北才能移动到第三个点。

对于一组不会发生旋转且会发生 180 度旋转的点,

[ ... (0, 2, 180), (1, 2, 90), (1, 1, 0), (1, 0, 90), ... ]

(0, 2)
处,您需要从朝北转向朝南才能继续前进,而对于
(1, 1)
,您已经面向正确的方向。

python list rotation coordinates maze
2个回答
0
投票

“...我如何向每个包含以 90 度为单位的旋转的元组添加第三个值?如果发生旋转,它应该返回旋转和方向,其中

-
表示反方向顺时针转动。假设您开始朝北。...”

您不需要旋转方向,只需要角度。

例如,

(3, 1, w)
的意思是,“移动到 3、1,并向西旋转”

n, e, s, w = 0, 90, 180, 270
p = [(3, 1, w), (3, 0, n), (2, 0, e),
     (2, 1, n), (1, 1, e), (1, 2, e), (1, 3, s), (2, 3, n),
     (1, 3, w), (1, 2, n), (0, 2, s),
     (1, 2, w), (1, 1, n), (0, 0, e), (0, 1, n)]

0
投票

要向每个包含以 90 度为增量的旋转的元组添加第三个值,您可以使用以下 Python 代码:

import math

def normalize_vector(vector):
    # Calculate the length of the vector
    length = math.sqrt(vector[0] ** 2 + vector[1] ** 2)
    if length == 0:
        return [0, 0]
    else:
        return [vector[0] / length, vector[1] / length]

def calculate_angle(vector1, vector2):
    # Calculate the angle in radians between two vectors
    angle_radians = math.atan2(vector2[1], vector2[0]) - math.atan2(vector1[1], vector1[0])
    
    # Convert radians to degrees
    angle_degrees = math.degrees(angle_radians)
    
    # Ensure the angle is in the range of -180 to 180 degrees
    if angle_degrees > 180:
        angle_degrees -= 360
    elif angle_degrees < -180:
        angle_degrees += 360
    
    return angle_degrees

# Example usage:
input_points = [
    [3, 1],
    [3, 0],
    [2, 0],
    # Add more points here...
]

current_direction = [-1, 0]

# Store the results in a list
result = []

for i, point in enumerate(input_points[:-1]):
    current_direction = normalize_vector(current_direction)
    next_direction = normalize_vector([input_points[i + 1][0] - point[0], input_points[i + 1][1] - point[1]])
    angle = -calculate_angle(current_direction, next_direction)

    # Ensure the angle is in the range of -180 to 180 degrees
    if angle > 180:
        angle -= 360
    elif angle < -180:
        angle += 360

    result.append([point[0], point[1], angle])
    current_direction = next_direction

# Print the result
print(result)

此代码将采用点列表作为输入,其中每个点表示为 [x, y]。它计算连续点之间的旋转角度,并将角度以 [x, y,rotation_angle] 格式附加到每个元组。 rotation_angle 以 90 度为增量,负号 (-) 表示逆时针旋转。

© www.soinside.com 2019 - 2024. All rights reserved.