java - 如何将嵌套的 for 循环转换为递归
问题描述
谁能帮我将这个 for 循环转换为递归方法:到目前为止,我添加了这两种方法,但我仍然想更改第二个循环。先感谢您。
public void makeDesign1() {
int x;
for (int i = 0; i < 5; i++) // For loop is the one creating the rows
{
for (x = 4; x > i; x--) // Nested loop is the one creating the columns
{
System.out.print("*");
}
System.out.println();
}
System.out.println();
}
public static int makeDesign1Recur(int i) {
if (i == 0) {
return 0;
}
System.out.print("*");
return (makeDesign1Recur(i-1));
}
// How to convert this second loop recursive?
public static void makeDesignRow(int i){
for ( int x = i; x>=0; x--){
makeDesign1Recur(x);
System.out.println("");
}
}
解决方案
我认为第一步是makeDesign1()
正确地重新定义。我们想为我们的绘图传递一个尺寸。我们还想稍微改变边界,让大小为 1 的时候画一颗星,而不是像原来的那样:
public static void makeDesign(int n)
{
for (int i = 0; i < n; i++) // For loop is the one creating the rows
{
for (int x = n; x > i; x--) // Nested loop is the one creating the columns
{
System.out.print("*");
}
System.out.println();
}
System.out.println();
}
下一步是让两个循环都倒计时到 1,以在时机成熟时简化递归:
public static void makeDesign(int n)
{
for (int i = n; i > 0; i--) // For loop is the one creating the rows
{
for (int x = i; x > 0; x--) // Nested loop is the one creating the columns
{
System.out.print("*");
}
System.out.println();
}
System.out.println();
}
现在我们可以简单地将每个循环转换成它自己的递归函数,一个调用另一个:
public static void makeDesign(int n)
{
if (n > 0)
{
makeDesignRow(n);
makeDesign(n - 1);
}
else
{
System.out.println();
}
}
public static void makeDesignRow(int x)
{
if (x > 0)
{
System.out.print("*");
makeDesignRow(x - 1);
}
else
{
System.out.println();
}
}
输出
传递makeDesign()
一个 10 的参数,我们得到:
> java Main
**********
*********
********
*******
******
*****
****
***
**
*
>
推荐阅读
- php - 更改位置 Controllers\Auth
- android - 建筑轮廓偏好类别
- python-3.x - 如何在 mqtt 中并行处理多条消息
- python - 如何在 x 轴上使用日期时间值设置条形宽度?
- python - ModuleNotFoundError:没有名为“加密”的模块。我已经安装了加密但仍然是同样的错误
- api - API 调用 Trustpilot
- html - 图像在 Microsoft Edge 中看起来不错,但在 Google Chrome 中不正确
- android - Jetpack 分页库无需滚动即可加载所有页面
- python - 标注城市名称
- excel - Excel 2016 根据排名更改评分标准