给定职位:
class Position {
private int x, y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
我想计算两个这样的位置之间的差异,然后让它返回一个位置列表,以将其结束。
例如:
Position oldPosition = new Position(10, 10);
Position newPosition = new Position(12, 10);
应该以传回清单[[10,10], [11,10], [12,10]]
。
我当前的代码:
Position oldPosition = new Position(10, 10);
Position newPosition = new Position(12, 12);
List<Position> fromOldToNewPositions = new ArrayList<>();
int differenceX = newPosition.getX() - oldPosition.getX();
int differenceY = newPosition.getY() - oldPosition.getY();
boolean xNegative = differenceX < 0;
boolean yNegative = differenceY < 0;
for (int x = oldPosition.getX(); xNegative && x >= newPosition.getX() || !xNegative && x <= newPosition.getX(); x = xNegative ? x - 1 : x + 1) {
for (int y = oldPosition.getY(); yNegative && y >= newPosition.getY() || !yNegative && y <= newPosition.getY(); y = yNegative ? y - 1 : y + 1) {
fromOldToNewPositions.add(new Position(x, y));
}
}
这样做很好,但是在结束位置是的情况下,12,12
它会返回一个列表:[[10,10], [10,11], [10,12], [11,10], [11,11], [11,12], [12,10], [12,11], [12,12]]
我希望结果为[[10,10], [11,11], [12,12]]
。
我将如何实现这种解决方案?
如果只允许您向左,向右,向上和向下移动,则需要先执行X方向上的所有步骤,然后再执行Y方向上的所有步骤。这意味着两个for循环是彼此相继的,而不是嵌套的。
如果允许使用对角线步长(看起来),则通常需要计算需要执行多少步max(diffX, diffY)
。然后采取尽可能多的步骤,其中一些是对角线步骤:
Position oldPosition = new Position(10, 10);
Position newPosition = new Position(14, 12);
List<Position> fromOldToNewPositions = new ArrayList<>();
int differenceX = newPosition.getX() - oldPosition.getX();
int differenceY = newPosition.getY() - oldPosition.getY();
int steps = Math.max(differenceX, differenceY);
for (int step = 0; step <= steps; step++) {
double part = step / (double)steps;
fromOldToNewPositions.add(new Position((int)(oldPosition.getX() + differenceX * part), (int)(oldPosition.getY() + differenceY * part)));
}
[[10 | 10], [11 | 10], [12 | 11], [13 | 11], [14 | 12]]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句