【发布时间】:2021-09-06 15:04:40
【问题描述】:
我正在尝试编写一个方法,它给出了两个范围为 0 到 1000 的 Point(X,Y):_startCoord 和 _endCoord。从_startCoord 到_endCoord 循环遍历二维数组lightMap,修改两点之间区域中的每个元素。
我以这个插图为例,我试图修改四边形 A 中的所有元素,给定:_startCoord 作为某个角点,_endCoord 作为对角点
我一直在尝试找出一种适用于任何“方向”的方法,例如:
来自500,500 to 250,750 WHERE x 递减,y 递增
或500,500 to 750,150WHERE x 递增,y 递减等
这是我最近的尝试:
struct Point {
public int xPos;
public int yPos;
public Point(int _x, int _y) {
xPos = _x;
yPos = _y;
}
}
//Given two corner points, toggle the elements between the points
static void ToggleBits(Point _startCoord, Point _endCoord) {
//Determine direction to iterate on each axis
int xDir = (_startCoord.xPos > _endCoord.xPos) ? -1 : 1;
int yDir = (_startCoord.yPos > _endCoord.yPos) ? -1 : 1;
int currentX = _startCoord.xPos;
int currentY = _startCoord.yPos;
//Account for single point (points are the same)
if (_startCoord.xPos == _endCoord.xPos && _startCoord.yPos == _endCoord.yPos) {
lightMap[currentX, currentY] = !lightMap[currentX, currentY]; //Toggle element at current indices
return;
}
//While both indices not met
while (currentX != _endCoord.xPos || currentY != _endCoord.yPos) {
Console.WriteLine(currentX + ","+currentY);
lightMap[currentX, currentY] = !lightMap[currentX, currentY]; //Toggle element at current indices
if (currentX == _endCoord.xPos) { //Reached endX
if (currentY != _endCoord.yPos) { //But not reached endY
currentY += yDir; //Increment y axis
currentX = _startCoord.xPos; //Return to column start
}
}
else if (currentY == _endCoord.yPos) { //Reached endY
if (currentX != _endCoord.xPos) { //But not reached endX
currentX += xDir; //Increment x axis
currentY = _startCoord.yPos; //Return to row start
}
} else { //Neither indices reached increment x axis
currentX += xDir; //Increment x axis
}
}
}
输入
ToggleBits(new Point(5,0), new Point(6,10));
输出
5,0
6,0
5,1
6,1
5,2
6,2
5,3
6,3
5,4
6,4
5,5
6,5
5,6
6,6
5,7
6,7
5,8
6,8
5,9
6,9
5,10
6,0
5,1
6,1
5,2
6,2
...Infinite Loop...
它非常接近正常工作,但是当我重置行/列并增加列/行时,我重置了进度并再次执行......永远。任何帮助表示赞赏,在此先感谢!
【问题讨论】: