gpt4 book ai didi

java - 绘制两棵特定高度的 ASCII 云杉树

转载 作者:行者123 更新时间:2023-12-04 13:05:00 28 4
gpt4 key购买 nike

我正在尝试编写生成这种形状的 ASCII 艺术的代码:

           *
***
*****
******* *
********* ***
*********** *****
********************
**********************
************************
**************************
****************************
******************************
代码需要能够根据输入高度生成此形状。
正如您从示例形状中看到的那样,我的代码使用 12 的行高正确生成了 ASCII 艺术。但是,对于 3、5、6、7、10、11、15 的行高,......它没有正确生成 ASCII 形状。我试图自己调试这个,但我找不到失败的行高之间的共性,这阻止了我用我的算法确定问题。
这是我用来生成 ASCII 艺术形状的 Java 代码(当然没有硬编码的 12 行高):
int h = 12;
for (int i = 0; i < h; i++) {
for (int j = 0; j < h - i; j++) {
System.out.print(" ");
}
for (int j = 0; j < i; j++) {
System.out.print("*");
}
for (int j = i; j >= 0; j--) {
System.out.print("*");
}
for (int j = 0; j < h / 2 - i; j++) {
System.out.print(" ");
}
for (int j = h / 2 - i; j > 0; j--) {
System.out.print(" ");
}
for (int j = 0; j <= h / 2; j++) {
if (i >= h / 2)
System.out.print("*");
}
for (int j = 0; j < i - h / 5; j++) {
if (i >= h / 4 && i < h / 2)
System.out.print("*");
}
for (int j = i - h / 5 - 1; j > 0; j--) {
if (i >= h / 4 && i < h / 2)
System.out.print("*");
}
System.out.println();
}
究竟是什么导致我的 ASCII 艺术生成器代码在某些行高上失败,我该如何解决代码的问题,以便它正确地为任何正整数生成 ASCII 艺术?

最佳答案

这通过具有 Shape 概括了问题。任何 ASCII 艺术形状的界面,以及 Spruce使用 intersects(x,y) 记录云杉形状的位置和高度的类以确定是否有任何坐标位于云杉上。
然后通过传入Spruce的列表可以更灵活地绘制并确定所有尺寸联合的每个点的命中/未命中。 Spruce可以整齐地定义为 JDK16 记录:

public record Spruce(int left, int height) implements Shape {
public int right() { return left+2*height-2; }
public int top() { return height; }

// Check any coordinate hits / misses this Spruce:
public boolean intersects(int x, int y) {
return 1 <= y && y <= height && x >= left + y - 1 && x <= left + 2 * height - 1 - y;
}
}
...和一个简单的主要绘制尽可能多的 Spruce/其他 Shape如所须:
public static void main(String[] args) {
Shape.draw(new Spruce(1, 4), new Spruce(6, 6));
Shape.draw(new Spruce(2, 6), new Spruce(10, 4));
Shape.draw(new Spruce(3, 10), new Spruce(30, 9), new Spruce(18, 5));
}
返回:
Spruce[left=1, height=4]
Spruce[left=6, height=6]

*
***
* *****
*** *******
**************
****************

Spruce[left=2, height=6]
Spruce[left=10, height=4]

*
***
***** *
******* ***
*************
***************

Spruce[left=3, height=10]
Spruce[left=30, height=9]
Spruce[left=18, height=5]

*
*** *
***** ***
******* *****
********* *******
*********** * *********
************* *** ***********
******************** *************
********************** ***************
************************ *****************

关于java - 绘制两棵特定高度的 ASCII 云杉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33815056/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com