Given a Position:
class Position {
private int x, y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
I would like to calculate the difference between two such positions and then have it return a list of positions that would get it to the end.
For example:
Position oldPosition = new Position(10, 10);
Position newPosition = new Position(12, 10);
Should return a list with:
[[10,10], [11,10], [12,10]]
My current code:
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));
}
}
Does this well, but in scenarios where the end position is 12,12 it returns a list:
[[10,10], [10,11], [10,12], [11,10], [11,11], [11,12], [12,10], [12,11], [12,12]]
where I would like the result to be:
[[10,10], [11,11], [12,12]]
How would I go about achieving such a solution?