gpt4 book ai didi

java - 如何以更干净的方式使用递归在沙漏下面进行编码?

转载 作者:行者123 更新时间:2023-12-02 09:36:40 24 4
gpt4 key购买 nike

最近,我遇到了一个关于在 java 中使用递归编码沙漏的小测验。我设法按如下方式对其进行编码,但希望接受是否有更好的编码方法。

下面是我完成的编码部分。

 public class Demo {
int initialInput = 0;
int noOfAsteriskForNextLine= 0 ;
int noOfSpace =1;
Boolean isReversed = false;`enter code here`
public static void main (String[] args){
Demo d = new Demo();
d.run();
}
public void printLineOfAsterisk(int noOfAsterisk){
if(initialInput== 0){
initialInput=noOfAsterisk;
}

if(noOfAsteriskForNextLine==0){
noOfAsteriskForNextLine=noOfAsterisk;
}

for(int i=0;i<noOfSpace;i++){
System.out.print(" ");
}
for(int i=0;i<noOfAsterisk;i++){
System.out.print(" *");
}
System.out.print("\n");
if(isReversed&&initialInput==noOfAsterisk){
return;
}
if(isReversed||noOfAsteriskForNextLine==1){
isReversed =true;
noOfAsteriskForNextLine++;
noOfSpace--;
printLineOfAsterisk(noOfAsteriskForNextLine);

}else{
noOfSpace++;
noOfAsteriskForNextLine--;
printLineOfAsterisk(noOfAsteriskForNextLine);
}
}
public void run(){
printLineOfAsterisk(4);
}

}

预期输出如下,取决于传入的参数

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

最佳答案

试试这个。这里 offset 就是 no。在星星之前给予的空间。最初,该函数将使用 offset = 0 调用,这意味着在第一行中不会打印空格。

starCount 是编号。打印空格后在行中打印的星星数。

increment 只是增加或减少编号。空格和星号最初是 1 意味着没有。下一次迭代中的空格数将增加 1 和 no。星星数量将减少 1

请参阅代码中的注释以获取更多说明

import java.util.*;

public class Main
{
public static void hourGlass(int offset, int starCount, int increment) {
// This is the terminating condition.
// If offset is negative and increment is also negative, it means that no. of spaces were positive before this function call.
// This implies that the lower half of the hourglass is completed,
// So just return from here without executing anything
if(offset < 0 && increment < 0)
return;

// Print spaces
for(int i=0; i<offset; i++)
System.out.print(" ");
// Print stars with a space
for(int i=0; i<starCount; i++)
System.out.print("* ");
// Print a new line
System.out.println();

// If no. of stars is 1, then it means the upper half is completed.
// So, here the increment is set to -1
// So that from next recursive call onwards stars will increase and spaces will decrease by 1
if(starCount == 1)
increment = -1;

// Call this function recursively
hourGlass(offset + increment, starCount - increment, increment);
}

public static void main(String[] args)
{
// first argument is no. of spaces which will be zero initially
// second arguments is number of starts, change it according to your need
// third argument is just to increment/decrement stars & spaces
Main.hourGlass(0, 5, 1);
}
}

输出:

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

关于java - 如何以更干净的方式使用递归在沙漏下面进行编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57452202/

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