0
\$\begingroup\$

To get points which lie on the border of a rectangle, I use 4 for loops. At first I thought about creating Rectangle and using PathItterator, but it confused me very much. Is there a better way than mine?

int r = 5;
int x = 0;
int y = 0;
int length = r * 2 + 1;
for (int i = 0; i < length; i++) {
    System.out.print(String.format("(%d,%d) ", x - r + i, y - r));
}
System.out.println();
for (int i = 0; i < length; i++) {
    System.out.print(String.format("(%d,%d) ", x - r + i, y + r));
}        System.out.println();

for (int i = 0; i < length; i++) {
    System.out.print(String.format("(%d,%d) ", x - r , y - r+i));
}        System.out.println();

for (int i = 0; i < length; i++) {
    System.out.print(String.format("(%d,%d) ", x + r , y - r+i));
}
System.out.println();
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

Most rectangles have a length and a width. I’ve never heard of a rectangle with a radius, but it would be known as a square.

More constructively:

System.out.print(String.format("(%d,%d) ", x - r + i, y - r));

Could be written as:

System.out.format("(%d,%d) ", x - r + i, y - r);
\$\endgroup\$
0
0
\$\begingroup\$

I hope you realize these things:

  1. You are using r as the offset of the top-left from the origin.
  2. You are using same length for width and height - so square
  3. Length should be 2*r rather than 2r (guessing you made it +1 to make the loop work)
  4. Your i should go from 0 to <=length. It should be inclusive range as you want to include both borders.

In other words, length = 2r. And for loop goes from i=0 to i<=length.

What do I mean by offset? The top-left corner will always be offset by (-r,-r) relative to the axes origin. As the length changes, only the bottom right corner will keep moving.

For example, if length is changed to length = 4r, then top-left corner will remain at (-r,-r) and bottom-right corner will move to (3r, 3r).

Here (+) represents the origin, and it is not at the center of the bigger square.

  ********************
  *                  *
  *                  *
  *                  *
  *                  *
  *    +             *
  *                  *
  *                  *
  *                  *
  ********************

You can better keep r=0, or remove the variable r completely, and just use length = 10. Then your square will start at (0,0) and go to (l, l).

If you want it to be a rectangle, you can use width and height instead of the common length.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.