如果只给出尺寸,你将如何使用Java递归打印钻石?
大小为5会产生:
***** *****
**** ****
*** ***
** **
* *
* *
** **
*** ***
**** ****
***** *****
Run Code Online (Sandbox Code Playgroud)
我到目前为止的守则
public static void dia(int statSize, int size,int count) {
int statSizeLarge = (statSize*2)+1;
// Params:
// statSize == static size, never change this
// size == variable size, change this
// count == counter
if(size==0) {
System.out.println();
} else {
// is the counter smaller then the size
// if yes, increment and keep printing
if(count<size){
System.out.print("*");
}
// is greater then size?
// if yes, move on, print
// a few more stars
if((count<=statSizeLarge)){
if(count<statSize+1 && (count>size)){
System.out.print(" ");
}else if (count>size+1){
System.out.print("*");
} else {}
dia(statSize,size,count+1);
}
// reset count, move to next element
if(count>=statSizeLarge) {
count = 0;
System.out.println();
dia(statSize,size-1,count);
}
} // ends Else
}
Run Code Online (Sandbox Code Playgroud)
输出:
Enter commands:
diamond 3
******
** ****
* ****
* ****
** ****
* ****
* ****
Run Code Online (Sandbox Code Playgroud)
要创建更大的钻石,请选择较小的钻石并添加两个额外的行和列.在下面的diagrom中,为了清晰起见,我用点替换空格.在第二颗钻石中,新添加的字符以粗体显示.
*****.***** <-- extra row
****.**** ****...****
***...*** ***.....***
**.....** **.......**
*.......* *.........*
......... --> ...........
*.......* *.........*
**.....** **.......**
***...*** ***.....***
****.**** ****...****
*****.***** <-- extra row
^^
||
extra columns
您的递归函数应该打印第一行,然后打印一个较小的菱形,中间有两个额外的列,然后是最后一行.
在伪代码中:
void diamond(stars, spaces) {
if (n == 0) {
print(' ' * spaces)
} else {
print('*' * stars, ' ' * spaces, '*' * stars)
diamond(stars - 1, spaces + 2)
print('*' * stars, ' ' * spaces, '*' * stars)
}
}
Run Code Online (Sandbox Code Playgroud)
由于这是一个学习练习,我不会给你完整的Java源代码 - 你可以自己编写它.在这里,您可以看到它在Python中在线运行,这样您就可以看到该算法有效:
| 归档时间: |
|
| 查看次数: |
4388 次 |
| 最近记录: |