Joseph L. answered 05/03/26
Tutor
New to Wyzant
Coding, Game Dev, AI and Tech Solutions Professional
using System;
public readonly struct Point2D
{
public double X { get; }
public double Y { get; }
public Point2D(double x, double y) { X = x; Y = y; }
public override string ToString() => $"({X:F2}, {Y:F2})";
}
public static class Rotation
{
public static Point2D[] RotateSquare(Point2D[] corners, double degrees)
{
if (corners.Length != 4)
throw new ArgumentException("Expected 4 corners.", nameof(corners));
// 1. Find the center (average of the four corners)
double centerX = (corners[0].X + corners[1].X + corners[2].X + corners[3].X) / 4.0;
double centerY = (corners[0].Y + corners[1].Y + corners[2].Y + corners[3].Y) / 4.0;
// 2. Convert degrees to radians, precompute sin and cos
double radians = degrees * Math.PI / 180.0;
double cos = Math.Cos(radians);
double sin = Math.Sin(radians);
// 3. Translate -> rotate -> translate back, for each corner
var rotated = new Point2D[4];
for (int i = 0; i < 4; i++)
{
double dx = corners[i].X - centerX;
double dy = corners[i].Y - centerY;
double newX = dx * cos - dy * sin + centerX;
double newY = dx * sin + dy * cos + centerY;
rotated[i] = new Point2D(newX, newY);
}
return rotated;
}
}
class Program
{
static void Main()
{
// A square with corners at (2,2), (6,2), (6,6), (2,6) — center at (4,4)
var square = new[]
{
new Point2D(2, 2),
new Point2D(6, 2),
new Point2D(6, 6),
new Point2D(2, 6),
};
var rotated = Rotation.RotateSquare(square, 45);
Console.WriteLine("Original:");
foreach (var p in square) Console.WriteLine(" " + p);
Console.WriteLine("Rotated 45°:");
foreach (var p in rotated) Console.WriteLine(" " + p);
}
}