gpt4 book ai didi

algorithm - 用 Java 输出类似英国国旗的 ASCII 艺术

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:26:04 26 4
gpt4 key购买 nike

我的任务是编写一个算法输出(以普通的 ASCII,没有花哨的图画),对于给定的 K,一个 KxK 正方形,其对称线为 x,其他东西为 o。但是,如果 K 是偶数,我们使用两条 x 线来标记水平和垂直对称线。此外,我们不能在整个源代码中使用两个以上的循环。

所以我有两个想法。第一个是分析每个点应该满足的坐标——每个点应该有一个方程告诉我们给定的 (Kx, Ky) 点是 x 还是 o。我们把它放在一些 if 和只是 while 循环中,遍历所有可能的 (Kx, Ky),将一些点标记为 x,将其他点标记为 y。这需要一个循环。

另一个想法,相当蛮力但没有让我们分析所有的点,是有一组变量,然后我们用它来连接字符串。让我解释一下:我们有一个 while 循环检查“height”变量(每转一圈我们将其减一),在其中我们使用一些 repeatString 的自定义方法,该方法也由一个 while 循环组成(它只是将字符串乘以给定t 次)。所以我们有这样的东西:

while(height):
if height==maxHeight OR ==0: print repeatString("x", maxWidth)
else if height is an element of markedKy (an array telling us which Ky's to mark as x'es as the whole): print repearString("x", maxWidth)
else print "x"+(howManySpaces*" ")+"x" ["xx" if even] + (howManySpaces*" ") +"x"

……等等。我上面写的当然很松散,并没有涵盖很多情况(实际上,它确实很少),但我认为这可能会使我的概念不那么困惑。然而,第二种方法编写代码时会非常痛苦 - 我现在才知道它是多么容易出错。

有没有第三种最好的方法?我正在为此绞尽脑汁,虽然它看起来很简单,但我想不出其他任何东西。

最佳答案

我可以只使用一个循环来完成...;-)

input K
half := K / 2 , square := K * K
for pixel = 0; pixel < square; ++pixel
horiz := pixel % K , vert := pixel / K
if horiz = vert or horiz + vert + 1 = K // the diagonals
or horiz = half or horiz = K - 1 - half // the middle vertical line(s)
or vert = half or vert = K - 1 - half // the middle horizontal line(s)
output "x"
else if ShouldBeO(horiz + 1, vert + 1)
output "o"
else
output " "
if horiz = K - 1 // add "and vert < K - 1" if you don't want the last EOL
output EndOfLine
end for

关于algorithm - 用 Java 输出类似英国国旗的 ASCII 艺术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13086561/

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