Another answer for fun, to try out JDK16 records. Rather than loop over the different indexes in a row, this Diamond shape uses Math.abs
in simple declaration:
public record Diamond(int midx, int midy, int size) implements Shape {
public int right() { return midx + size; }
public int top() { return midy + size; }
/** Check if shape is drawn at this x,y position */
public boolean intersects(int x, int y) {
return Math.abs(midx-x) + Math.abs(midy-y) <= size;
}
}
Add interface for all Shape
classes and a general purpose draw
to print out asterisks for any intersecting shape:
public interface Shape {
/** Check if shape is drawn at this x,y position */
boolean intersects(int x, int y);
/** Max X position used by this shape */
int right();
/** Max Y position used by this shape */
int top();
/** Draw a series of shapes */
public static void draw(Shape ... shapes) {
// Work out largest X, Y coordinates (and print the shape list):
int ymax = Arrays.stream(shapes).peek(System.out::println)
.mapToInt(Shape::top ).max().getAsInt();
int xmax = Arrays.stream(shapes).mapToInt(Shape::right).max().getAsInt();
System.out.println();
// Visit all X,Y and see what will be printed
for (int y = ymax ; y > 0; y--) {
for (int x = 1 ; x <= xmax; x++) {
boolean hit = false;
for (int i = 0; !hit && i < shapes.length; i++) {
hit = shapes[i].intersects(x,y);
}
System.out.print(hit ? "*" : " ");
}
System.out.println();
}
System.out.println();
}
}
... and a main to draw as many shapes as you wish - it is easy to define new ASCII art Shape
classes:
public static void main(String[] args) {
Shape.draw(new Diamond(10, 7, 5));
Shape.draw(new Diamond(10, 7, 3), new Diamond(17, 5, 3), new Diamond(22, 8, 1));
}
This prints:
Diamond[midx=10, midy=7, size=5]
*
***
*****
*******
*********
***********
*********
*******
*****
***
*
Diamond[midx=8, midy=7, size=5]
Diamond[midx=17, midy=5, size=3]
Diamond[midx=22, midy=8, size=1]
*
***
*****
******* *
********* * ***
*********** *** *
********* *****
******* *******
***** *****
*** ***
* *
See also: Draw two ASCII spruce trees of specific heights