java - 如何递归地做我的金字塔数字模式?
问题描述
我必须使用递归方法制作这种模式我让它在 main 中打印出不正确的数字我这样称呼它 int n = 5; a.模式(n,n);
static void print_space(int space)
{
// base case
if (space == 0)
return;
System.out.print(" ");
// recursively calling print_space()
print_space(space - 1);
}
// function to print numbers
static void print_numbers(int numbers)
{
// base case
if (numbers == 0)
return;
System.out.print("1 ");
// recursively calling numbers()
print_numbers(numbers - 1);
}
// function to print the pattern
static void pattern(int n, int num)
{
// base case
if (n == 0)
return;
print_space(n - 1);
print_numbers(num - n + 1);
print_numbers(num - n);
System.out.println("");
// recursively calling pattern()
pattern(n - 1, num);
}
}
最后应该是这样的,但我有这样的
1 1
212 211
32123 32121
4321321
等等......谢谢!
解决方案
这个金字塔...
*********1*********
********212********
*******32123*******
******4321234******
*****543212345*****
****65432123456****
***7654321234567***
**876543212345678**
*98765432123456789*
... 是这种递归方法的结果,没有空格和数字的方法:
public class RecursivePyramid {
public static void WriteOutPyramidLevel(int level,int height) {
// Need counter in loops
int counter;
// Writing spaces in front - using asterix for visible debugging
for (counter=height ;counter > level; counter-- )
System.out.print("*");
// Writing numbers in front
for (counter=level ;counter > 1; counter-- )
System.out.print(counter);
// Writing central «line» in Pyramid
System.out.print(1);
// Writing numbers after central line
for (counter=2 ;counter <= level; counter++ )
System.out.print(counter);
// Writing spaces after central line - can of course be removed
for (counter=level ;counter < height; counter++)
System.out.print("*");
// Line finished
System.out.println();
// If below height of Pyramid go again - max 9 allowed
if (level < height && level < 9)
WriteOutPyramidLevel(level+1,height);
}
public static void main(String[] parameters) {
WriteOutPyramidLevel(1,10);
}
}
推荐阅读
- delphi - 无法在 Delphi 10.2 中将 char 数组分配给字符串
- python - 如何在python 3.7中的aa Tk画布内创建一个按钮
- javascript - 以响应方式将 Highcharts 工具提示置于圆环图中间
- php - 通过 PHP 和 Laravel if 语句的暗模式
- android - 从输入流下载图像显示损坏的图像
- c# - 如何在 C# 中生成带有向下旋转 90 度的字母的 Excel 文件?
- node.js - 如何取消队列中的特定作业?
- haskell - 在 Haskell 中执行保护子句之前对列表进行排序
- amazon-web-services - 我想设置一个安全组只允许 ELB 到 ec2
- python - 在 SQLAlchemy 模型中查询数据库