Java:递归打印钻石 [英] Java: Print a diamond recursively
问题描述
如果只给出尺寸,你将如何使用Java递归打印钻石?
How would you print a diamond recursively using Java with only given the size?
5的大小产生:
***** *****
**** ****
*** ***
** **
* *
* *
** **
*** ***
**** ****
***** *****
我到目前为止的代码
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
}
OutPut:
Enter commands:
diamond 3
******
** ****
* ****
* ****
** ****
* ****
* ****
推荐答案
要创建更大的钻石,请选择较小的钻石并添加两个额外的行和列。在下面的diagrom中,为了清晰起见,我用点替换空格。在第二颗钻石中,新添加的字符以粗体显示。
To create a larger diamond, take a smaller one and add two extra rows and columns. In the diagrom below I've replace spaces with dots for clarity. In the second diamond the newly added characters are shown in bold.
*****.***** <-- extra row
****.**** ****...****
***...*** ***.....***
**.....** **.......**
*.......* *.........*
......... --> ...........
*.......* *.........*
**.....** **.......**
***...*** ***.....***
****.**** ****...****
*****.***** <-- extra row
^^
||
extra columns
您的递归函数应该打印第一行,然后打印一个较小的钻石,中间有两个额外的列,然后是最后一行。
Your recursive function should print the first row, then print a smaller diamond with two extra columns in the middle, then the last row.
在伪代码中:
void diamond(stars, spaces) {
if (n == 0) {
print(' ' * spaces)
} else {
print('*' * stars, ' ' * spaces, '*' * stars)
diamond(stars - 1, spaces + 2)
print('*' * stars, ' ' * spaces, '*' * stars)
}
}
由于这是一个学习练习,我不会给你完整的Java源代码代码 - 您可以自己编写代码。在这里你可以看到它在Python上运行,只是为了让你看到算法有效:
Since this is a learning exercise I won't give you the full Java source code - you can have a go at writing it yourself. Here you can see it running online in Python, just so that you can see that the algorithm works:
- ideone
这篇关于Java:递归打印钻石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!