将2D阵列旋转45度
问题描述:
如何旋转奇数行45度的整数的二维矩形阵列?将2D阵列旋转45度
因此,像
int[] myArray = new int[,]
{
{1, 0 ,1},
{0, 1 ,0},
{0, 0 ,0},
}
到
int[] rotatedArray = new int[,]
{
{0, 1 ,0},
{0, 1 ,1},
{0, 0 ,0},
}
任何尺寸(3x3的,5x5的,7x7的,等等)。由该式http://yfrog.com/n6matrix45p
5x5的
0 0 0 0 0
2 0 0 0 0
1 1 1 1 1
0 0 0 0 0
0 0 0 0 0
成
1 2 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
5x5的
0 0 0 3 0
0 0 0 3 0
0 0 0 3 0
0 0 0 3 0
0 0 0 3 0
成
0 0 0 0 0
0 0 0 0 3
0 0 0 3 0
0 0 3 3 0
0 3 0 0 0
答
这是我写的代码,并可以解决这个朋友:
public static class ArrayExtensions
{
public static Point RoundIndexToPoint(int index, int radius)
{
if (radius == 0)
return new Point(0, 0);
Point result = new Point(-radius, -radius);
while (index < 0) index += radius * 8;
index = index % (radius * 8);
int edgeLen = radius * 2;
if (index < edgeLen)
{
result.X += index;
}
else if ((index -= edgeLen) < edgeLen)
{
result.X = radius;
result.Y += index;
}
else if ((index -= edgeLen) < edgeLen)
{
result.X = radius - index;
result.Y = radius;
}
else if ((index -= edgeLen) < edgeLen)
{
result.Y = radius - index;
}
return result;
}
public static T[,] Rotate45<T>(this T[,] array)
{
int dim = Math.Max(array.GetLength(0), array.GetLength(0));
T[,] result = new T[dim, dim];
Point center = new Point((result.GetLength(0) - 1)/2, (result.GetLength(1) - 1)/2);
Point center2 = new Point((array.GetLength(0) - 1)/2, (array.GetLength(1) - 1)/2);
for (int r = 0; r <= (dim - 1)/2; r++)
{
for (int i = 0; i <= r * 8; i++)
{
Point source = RoundIndexToPoint(i, r);
Point target = RoundIndexToPoint(i + r, r);
if (!(center2.X + source.X < 0 || center2.Y + source.Y < 0 || center2.X + source.X >= array.GetLength(0) || center2.Y + source.Y >= array.GetLength(1)))
result[center.X + target.X, center.Y + target.Y] = array[center2.X + source.X, center2.Y + source.Y];
}
}
return result;
}
}
答
你可以试试这个库:
Math.NET Project为矩阵操作... http://numerics.mathdotnet.com/
此代码似乎是太有用:
http://www.drunkenhyena.com/cgi-bin/view_net_article.pl?chapter=2;article=28#Rotation
不要忘了DirectX托管和非托管名称空间和类。很多 和很多好东西在那里检查。
例如:
答
我认为我们有以下规则:
想象矩阵中的每个其他类似的“俄罗斯一组“框架或箱子没有中心”娃娃”。
一侧(顶部/左侧/右侧/底部)中心的元素顺时针移动到最近的角落。
角落顺时针移向下一个中心。
不是拐角也不是中心的元素移动到距离拐角相同距离的下一个点(顺时针)。
我已经开始写一些代码,但我不认为这是小事,我还没有时间来检验。
这些矩阵只有4×4或3×3,我会尽力math.net,但我担心这种旋转是过于具体 – Kikaimaru 2010-07-19 07:59:08
这些是用于转换的旋转矩阵。完全不同的事情。 – Cloudanger 2010-07-19 08:52:54