Java:递归打印钻石

发布于 2024-10-19 12:51:16 字数 1562 浏览 1 评论 0原文

如何使用 Java 在给定尺寸的情况下递归打印钻石?

大小为 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  

  }

输出:

Enter commands:
diamond 3
******
** ****
*  ****




*  ****




** ****
*  ****




*  ****

How would you print a diamond recursively using Java with only given the size?

A size of 5 produces:

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

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

Code I have so far

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
******
** ****
*  ****




*  ****




** ****
*  ****




*  ****

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

痴骨ら 2024-10-26 12:51:16

要创建更大的钻石,请使用较小的钻石并添加额外的两行和两列。在下图中,为了清晰起见,我用点替换了空格。在第二个菱形中,新添加的字符以粗体显示。

              *****.*****  <-- 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)
    }
}

由于这是一个学习练习,我不会向您提供完整的 Java 源代码 - 您可以尝试自己编写它。这里你可以看到它在Python中在线运行,这样你就可以看到算法是有效的:

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.

In pseudocode:

void diamond(stars, spaces) {
    if (n == 0) {
        print(' ' * spaces)
    } else {
        print('*' * stars, ' ' * spaces, '*' * stars)
        diamond(stars - 1, spaces + 2)
        print('*' * stars, ' ' * spaces, '*' * stars)
    }
}

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:

前事休说 2024-10-26 12:51:16

提示:在输出中查找模式。尝试将该模式映射到递归调用上,其中方法执行某些操作,调用自身,然后执行其他操作。

Hint: look for the pattern in the output. Try to map that pattern onto recursive calls, where a method does something, calls itself, and then does something else.

极度宠爱 2024-10-26 12:51:16

下面是打印星星钻石的 Java 程序:

class DiamondPattern {
    static public int ReadInteger() {
        try {
            String inpString = "";
            InputStreamReader input = new InputStreamReader(System.in);
            BufferedReader reader = new BufferedReader(input);
            String s = reader.readLine();
            return Integer.parseInt(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    public static void main(String[] args) {
        System.out.println("Program for displaying pattern of *.");
        System.out.print("Enter the maximum number of *: ");
        int n = ReadInteger();

        System.out.println("\nHere is the Diamond of Stars\n");

        for (int i = 1; i <= n; i++) {
            for (int j = 0; j < (n - i); j++)
                System.out.print(" ");
            for (int j = 1; j <= i; j++)
                System.out.print("*");
            for (int k = 1; k < i; k++)
                System.out.print("*");
            System.out.println();
        }

        for (int i = n - 1; i >= 1; i--) {
            for (int j = 0; j < (n - i); j++)
                System.out.print(" ");
            for (int j = 1; j <= i; j++)
                System.out.print("*");
            for (int k = 1; k < i; k++)
                System.out.print("*");
            System.out.println();
        }
        System.out.println();
    }
}

Here is the Java Program to print the diamond of stars:

class DiamondPattern {
    static public int ReadInteger() {
        try {
            String inpString = "";
            InputStreamReader input = new InputStreamReader(System.in);
            BufferedReader reader = new BufferedReader(input);
            String s = reader.readLine();
            return Integer.parseInt(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    public static void main(String[] args) {
        System.out.println("Program for displaying pattern of *.");
        System.out.print("Enter the maximum number of *: ");
        int n = ReadInteger();

        System.out.println("\nHere is the Diamond of Stars\n");

        for (int i = 1; i <= n; i++) {
            for (int j = 0; j < (n - i); j++)
                System.out.print(" ");
            for (int j = 1; j <= i; j++)
                System.out.print("*");
            for (int k = 1; k < i; k++)
                System.out.print("*");
            System.out.println();
        }

        for (int i = n - 1; i >= 1; i--) {
            for (int j = 0; j < (n - i); j++)
                System.out.print(" ");
            for (int j = 1; j <= i; j++)
                System.out.print("*");
            for (int k = 1; k < i; k++)
                System.out.print("*");
            System.out.println();
        }
        System.out.println();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文