我想根据当前位置将矩阵分成象限,左上角和左下角。这是一个例子(为了避免编写T / U,例如,我放置了具有顶部和左边优先级的不同字符,但它们确实重叠):
o T T U o o o
B T X U L L L
B B B L L L L
B B B L L L L
o o L L L L L
o o L L L L L
X是核心要素。 o是一个未包含在任何象限中的元素,T是左上角,U是右上角,B是左下角,L是右下角,我希望你能得到这个想法。我的解决方案包括检查起始位置的矩阵的哪个象限,然后相应地制作象限,这使得总共4个案例每个有4个象限= 16.我希望有更好的方法,所以你能帮助我吗?这个?我正在用C#编写程序,但伪代码很好。
答案 0 :(得分:1)
您可以通过各自的财产访问笛卡尔系统的不同象限。
public class Matrix<T>
{
public T[,] Elements { get; private set; }
public int Size { get; private set; }
public Point CentralPoint { get; set; }
public T this [int y, int x]
{
get { return Elements[y, x]; }
set { Elements[y, x] = value; }
}
public Matrix(int size)
{
this.Size = size;
this.Elements = new T[Size, Size];
}
public T[,] FirstQuadrant { get { return FromCentralTo(Size - 1, 0); } }
public T[,] SecondQuadrant { get { return FromCentralTo(0, 0); } }
public T[,] ThirdQuadrant { get { return FromCentralTo(0, Size - 1); } }
public T[,] FourthQuadrant { get { return FromCentralTo(Size - 1 , Size - 1); } }
private T[,] FromCentralTo(int x1, int y1, [CallerMemberName]string caller = "")
{
var translate = Math.Min(Math.Abs(CentralPoint.X - x1), Math.Abs(CentralPoint.Y - y1));
//fix the p1, so this results in a square array
if (Math.Abs(CentralPoint.X - x1) > translate)
x1 = CentralPoint.X + translate * Math.Sign(x1 - CentralPoint.X);
if (Math.Abs(CentralPoint.Y - y1) > translate)
y1 = CentralPoint.Y + translate * Math.Sign(y1 - CentralPoint.Y);
var size = translate + 1;
var start = new Point(Math.Min(CentralPoint.Y, y1), Math.Min(CentralPoint.X, x1));
var result = new T[size, size];
for (int x = 0; x < size; x++)
for (int y = 0; y < size; y++)
result[y, x] = this[start.Y + y, start.X + x];
return result;
}
}
public struct Point
{
public int X, Y;
public Point(int y, int x) { this.X = x; this.Y = y; }
}
void Main()
{
var matrix = new Matrix<int>(7);
matrix.CentralPoint = new Point(1, 2);
int i = 0;
for(int x = 0; x < 7; x++)
for (int y = 0; y < 7; y++)
matrix[x, y] = i++;
matrix.Elements.Dump("Matrix");
matrix[matrix.CentralPoint.Y, matrix.CentralPoint.X].Dump("Central");
matrix.FirstQuadrant.Dump("1");
matrix.SecondQuadrant.Dump("2");
matrix.ThirdQuadrant.Dump("3");
matrix.FourthQuadrant.Dump("4");
}
以上代码在LINQPad中产生以下内容: