I have a rectangle defined by its four corners on a Cartesian coordinate system. The rectangle consist of identically sized cells.
Given one of the corner cells as a starting point and a direction (either along x or y axis) how can I traverse this grid in snake like pattern?
For example, here (x4, y4) is the starting cell and direction is defined to be along the x axis. Blue line depicts the desired path.
Thanks!
Try the 4 pair of points to find the opposite point that defines the box. Then you have a Start and an Opposite pair of points. In your case, followAlongX will be an input so it's not needed to test the direction but I added a classic decision text otherwise.
In the end, try something like (Java, written in Notepad, not tested):
int stepY, stepX, yMin, yMax, yOpposite, yStart, xMin, xMax, xOpposite, xStart;
if (yOpposite > yStart) {
stepY = 1;
yMin = yStart;
yMax = yOpposite;
}
else {
stepY = -1;
yMax = yStart;
yMin = yOpposite;
}
if (xOpposite > xStart) {
stepX = -1;
xMin = xStart;
xMax = xOpposite;
}
else {
stepX = 1;
xMin = xOpposite;
xMax = xStart;
}
// boolean followAlongX = false;
// if (xMax-xMin>yMax-yMin) {
// loopOnX = true;
// }
List<Points> path = new ArrayList<>();
if (followAlongX) {
for (int i=yMin; i!=yMax; i+=stepY) {
for (int j=xmin; j!=xmax; j+=stepX) {
path.add(new Point(i,j));
}
stepX = -stepX;
int temp = xMin;
xMin = xMax;
xMax = temp;
}
}
else {
for (int j=xmin; j!=xmax; j+=stepX) {
for (int i=yMin; i!=yMax; i+=stepY) {
path.add(new Point(i,j));
}
stepY = -stepY;
int temp = yMin;
yMin = yMax;
yMax = temp;
}
}
return path.toArray(new Point[path.size()]);