Точки из повернутого прямоугольника
Extend a rectangle sampling function so it can sample points from a rotated rectangle.
The rectangle is described by its center, width, height and rotation angle. A sample (u, v) from the unit square should first be mapped to local rectangle coordinates and then rotated around the rectangle center.
Return the generated points in global coordinates.
Решение прямо на странице
Напишите код, запустите проверки и только потом открывайте разбор.
Нажмите «Запустить проверки» или Ctrl+Enter.
Показать разбор
Подсказки
- Сначала локальные координаты
Sample (0.5, 0.5) должен перейти в центр прямоугольника.
- Порядок операций
Сначала scale в локальных координатах, затем rotation, затем translation.
Идея решения
Сначала переводим u, v из [0, 1] в локальные координаты прямоугольника:
x = (u - 0.5) * width, y = (v - 0.5) * height.
Потом применяем rotation matrix:
[cos(a) -sin(a)]
[sin(a) cos(a)]
И прибавляем координаты центра. Для стабильных автотестов округляем каждую координату до 6 знаков.
Эталонный код
def rotated_rectangle_points(
center: list[float],
width: float,
height: float,
angle_rad: float,
samples: list[list[float]],
) -> list[list[float]]:
import math
cx, cy = center
cos_a = math.cos(angle_rad)
sin_a = math.sin(angle_rad)
result: list[list[float]] = []
for u, v in samples:
local_x = (u - 0.5) * width
local_y = (v - 0.5) * height
rotated_x = local_x * cos_a - local_y * sin_a
rotated_y = local_x * sin_a + local_y * cos_a
result.append([
round(cx + rotated_x, 6),
round(cy + rotated_y, 6),
])
return result