【问题标题】:Empty diamond shape with numbers带数字的空菱形
【发布时间】:2017-11-22 07:36:00
【问题描述】:

所以有人问我这个问题,我只能解决代码的顶部,我被困在底部。

编写一个名为EmptyDiamond.java 的Java 程序,其中包含一个方法,该方法采用整数n 并在2n − 1 行上打印一个空菱形,如下所示。示例输出 where n = 3:

  1
 2 2
3   3
 2 2
  1

到目前为止,这是我的代码:

public static void shape(int n) {
    //TOP PART
    for (int i = 1; i <= (n - 1); i++) {
        System.out.print(" ");
    }
    System.out.println(1);
    for (int i = 2; i <= n; i++) {
        for (int j = 1; j <= (n - i); j++) {
            System.out.print(" ");
        }
        System.out.print(i);
        for (int j = 1; j <= 2 * i - n + 1; j++) {
            System.out.print(" ");
        }
        System.out.println(i);
    }

    //BOTTOM PART (The messed up part)
    for (int i = n + 1; i <= 2 * n - 2; i++) {
        for (int j = 1; j <= n - i; j++) {
            System.out.print(" ");
        }
        System.out.print(i);
        for (int j = 1; j <= n; j++) {
            System.out.print(" ");
        }
        System.out.print(i);
    }
    for (int i = 1; i <= (n - 1); i++) {
        System.out.print(" ");
    }
    System.out.println(1);
}
public static void main(String[] args) {
    shape(4);
}

【问题讨论】:

    标签: java ascii-art


    【解决方案1】:

    可能有点晚了,但由于您的消息的底部只是镜像的第一部分,您可以使用Stack 以相反的顺序打印消息:

    public static void main(String[] args) {
        int maxNumber = 3;
        Stack<String> message = new Stack<>();
        // upper part
        for (int row = 0; row < maxNumber; row++) {
            int prefix = maxNumber - (row + 1);
            int spaces = row >= 2 ? row * 2 - 1 : row;
    
            String line = getLine(row, prefix, spaces);
            System.out.println(line);
            if (row != maxNumber - 1)
                message.add(line);
        }
        // bottom part
        while (!message.isEmpty())
            System.out.println(message.pop());
    }
    
    public static String getLine(int row, int prefix, int spaces) {
        StringBuilder line = new StringBuilder("_".repeat(prefix));
        line.append(row + 1);
        if (row != 0) {
            line.append("_".repeat(spaces));
            line.append(row + 1);
        }
        return line.toString();
    }
    

    输出:

    __1
    _2_2
    3___3
    _2_2
    __1
    

    您当然可以使用任何您想要填充堆栈的方法(即生成消息的上部),就像这个问题建议的方法一样。我描述的这个上部包含第一行(包括)到中间行(不包括)。

    【讨论】:

      【解决方案2】:

      这是打印空钻石的程序:

      int n = 3; //change the value of n to increase the size of diamond
      int upperCount = 1;
      for (int i = n; i >= 1; i--) {
          for (int j = i; j >= 1; j--) {
              System.out.print(" ");
          }
          System.out.print(upperCount);
          for (int j = 0; j <= upperCount - 2; j++) {
              System.out.print(" ");
          }
          for (int j = 0; j <= upperCount - 2; j++) {
              System.out.print(" ");
          }
          if (upperCount != 1) {
              System.out.print(upperCount);
          }
          upperCount++;
          System.out.print("\n");
      }
      
      int lowerCount = n - 1;
      for (int i = 1; i <= n - 1; i++) {
          for (int j = 0; j <= i; j++) {
              System.out.print(" ");
          }
          System.out.print(lowerCount);
          for (int j = 0; j <= lowerCount - 2; j++) {
              System.out.print(" ");
          }
          for (int j = 0; j <= lowerCount - 2; j++) {
              System.out.print(" ");
          }
          if (lowerCount != 1) {
              System.out.print(lowerCount);
          }
          lowerCount--;
          System.out.print("\n");
      }
      

      在代码的底部进行以下更改:

      int lowerCount = n - 1;
      for (int i = n - 1; i >= 2; i--) {
          for (int j = 1; j <= (n - i); j++) {
              System.out.print(" ");
          }
          System.out.print(i);
      
          for (int j = 1; j <= lowerCount; j++) {
              System.out.print(" ");
          }
          System.out.print(i);
          lowerCount -= 2;
      }
      

      【讨论】:

        【解决方案3】:

        您可以在从-nn 的行和列上使用两个嵌套的for 循环打印带有数字的空菱形iAbs + jAbs == n时得到菱形:

        int n = 2;
        for (int i = -n; i <= n; i++) {
            // absolute value of 'i'
            int iAbs = Math.abs(i);
            for (int j = -n; j <= n; j++) {
                // absolute value of 'j'
                int jAbs = Math.abs(j);
                // empty diamond shape
                System.out.print(iAbs + jAbs == n ? jAbs + 1 : " ");
                if (j < n) {
                    System.out.print(" ");
                } else {
                    System.out.println();
                }
            }
        }
        

        输出:

            1    
          2   2  
        3       3
          2   2  
            1    
        

        你可以分别定义widthheight

        int m = 4;
        int n = 2;
        int max = Math.max(m, n);
        for (int i = -m; i <= m; i++) {
            // absolute value of 'i'
            int iAbs = Math.abs(i);
            for (int j = -n; j <= n; j++) {
                // absolute value of 'j'
                int jAbs = Math.abs(j);
                // empty diamond shape
                System.out.print(iAbs + jAbs == max ? jAbs + 1 : " ");
                if (j < n) {
                    System.out.print(" ");
                } else {
                    System.out.println();
                }
            }
        }
        

        输出:

            1    
          2   2  
        3       3
                 
                 
                 
        3       3
          2   2  
            1    
        

        另见:
        Filling a 2d array with numbers in a rhombus form
        How to print a diamond of random numbers?

        【讨论】:

          【解决方案4】:

          java-11

          使用作为 Java-11 的一部分引入的String#repeat,您可以使用单循环来完成。

          public class Main {
              public static void main(String[] args) {
                  int n = 3;
                  for (int i = 1 - n; i < n; i++) {
                      int x = Math.abs(i);
                      System.out.println(" ".repeat(x) + (n - x)
                              + " ".repeat(Math.abs((n - x) * 2 - 3))
                              + ((i == 1 - n || i == n - 1) ? "" : (n - x)));
                  }
              }
          }
          

          输出:

            1 
           2 2
          3   3
           2 2
            1 
          

          您只需将空格量增加一个字符即可打印菱形的变体:

          public class Main {
              public static void main(String[] args) {
                  int n = 3;
                  for (int i = 1 - n; i < n; i++) {
                      int x = Math.abs(i);
                      System.out.println("  ".repeat(x) + (n - x)
                              + "  ".repeat(Math.abs((n - x) * 2 - 3))
                              + ((i == 1 - n || i == n - 1) ? "" : (n - x)));
                  }
              }
          }
          

          输出:

              1  
            2  2
          3      3
            2  2
              1  
          

          【讨论】:

            【解决方案5】:

            替代解决方案:

            public static void main(String[] args) {
              int n = 7;
              for (int i = -n; i <= n; i++) {
                for (int j = -n; j <= n; j++) {
                  // edge of the diamond
                  int edge = Math.abs(i) + Math.abs(j);
                  // diamond shape with numbers
                  if (edge == n) System.out.print(n - Math.abs(i) + 1);
                  // beyond the edge && in chessboard order || vertical borders
                  else if (edge > n && (i + j) % 2 != 0 || Math.abs(j) == n)
                    System.out.print("*");
                  // empty part
                  else System.out.print(" ");
                }
                System.out.println();
              }
            }
            

            输出:

            ** * * 1 * * **
            * * * 2 2 * * *
            ** * 3   3 * **
            * * 4     4 * *
            ** 5       5 **
            * 6         6 *
            *7           7*
            8             8
            *7           7*
            * 6         6 *
            ** 5       5 **
            * * 4     4 * *
            ** * 3   3 * **
            * * * 2 2 * * *
            ** * * 1 * * **
            

            另见:How to print a given diamond pattern in Java?

            【讨论】:

              【解决方案6】:

              解决方案:名为 EmptyDiamond.java 的 Java 程序包含一个方法,该方法采用整数 n 并在 2n − 1 行上打印一个空菱形。

              public class EmptyDiamond {
                  public static void main(String[] args) {
                      shape(3); // Change n to increase size of diamond
                  }
              
                  public static void shape(int n) {
                      int max = 2 * n - 1; // length of the diamond - top to bottom
                      int loop = 0; // with of each loop. initialized with 0
                      for (int i = 1; i <= max; i++) {
                          int val = 0;
                          if (i <= n) {
                              loop = n + i - 1;// e.g. when i = 2 and n = 3 loop 4 times
                              val = i; // value to be printed in each loop ascending
                          } else {
                              loop = n + (max - i); //e.g. when i = 4 and n = 3 loop 4 times
                              val = max - i + 1; // value to be printed in each loop descending
                          }
                          for (int j = 1; j <= loop; j++) {
                              // (value end of loop)
                              // || (value in the beginning  when i <= n)
                              // || (value in the beginning  when i > n)
                              if (j == loop
                                      || j == (n - i + 1)
                                      || j == (n - val + 1)) {
                                  System.out.print(val); // Print values
                              } else {
                                  System.out.print(" "); // Print space
                              }
                          }
                          System.out.println(); // Print next line
                      }
                  }
              }
              

              n = 3时输出:

                1
               2 2
              3   3
               2 2
                1
              

              【讨论】:

                【解决方案7】:

                仅流功能:

                public static void printEmptyDiamond(int n) {
                   IntStream.range(1, 2*n)
                        .map(i-> i > n ? 2*n-i : i)
                        .mapToObj(i -> " ".repeat(n-i) + i + (i>1 ? " ".repeat(2*(i-1)-1)+i : ""))
                        .forEach(System.out::println);
                }
                

                示例输出 (printEmptyDiamond(7)):

                      1
                     2 2
                    3   3
                   4     4
                  5       5
                 6         6
                7           7
                 6         6
                  5       5
                   4     4
                    3   3
                     2 2
                      1
                

                附解释:

                public static void printEmptyDiamond(int n) {
                   IntStream.range(1, 2*n)
                        .map(i-> i > n? 2*n-i : i) // numbers from 1 to n ascending, then descending to 1 again
                        .mapToObj(i -> " ".repeat(n-i) // leading spaces
                            + i // leading number
                            + (i>1 ? // only when number is > 1
                                " ".repeat(2*(i-1)-1) // middle spaces
                                 + i // trailing number
                            : ""))
                        .forEach (System.out::println);
                }
                

                【讨论】:

                  【解决方案8】:

                  我这样做是为了好玩,这是代码:

                  import java.util.Scanner;
                  
                  public class Diamond {
                      public static void main(String[] args) {
                          Scanner read = new Scanner(System.in);
                          int num = read.nextInt();
                          read.nextLine();
                          //TOP
                          for(int i = 1;i<=num;i++) {
                              //LEFT
                              for(int k = i; k<num;k++) {
                                  if ( k % 2 == 0 ) {
                                      System.out.print(" ");
                                  }
                              else {
                                  System.out.print(" ");
                              }
                          }
                          if(i>1) {
                              for(int j =1;j<=i;j++) {
                                  if (j==1 || j== i) {
                                      for(int u=0;u<j;u++) {
                                          System.out.print(" ");
                                      }
                                      System.out.print(i);
                                      
                                  }
                                  else {
                                      System.out.print(" ");
                                  }
                              }
                              System.out.println("");
                          }
                          else {
                              System.out.println("  "+i);
                          }
                      }
                      //BOTTOM
                      for(int i = num-1;i>0;i--) {
                          for(int k = i; k<num;k++) {
                              if ( k % 2 == 0 ) {
                                  System.out.print(" ");
                              }
                              else {
                                  System.out.print(" ");
                              }
                          }
                          if(i>1) {
                              for(int j =1;j<=i;j++) {
                                  if (j==1 || j== i) {
                                      for(int u=0;u<j;u++) {
                                          System.out.print(" ");
                                      }
                                      System.out.print(i);
                                  }
                                  else {
                                      System.out.print(" ");
                                  }
                              }
                              System.out.println("");
                          }
                          else {
                              System.out.println(" "+i);
                          }
                      }
                  }
                  }
                  

                  还有输出:

                      7
                          1
                        2  2
                       3    3
                      4      4
                     5        5
                    6          6
                   7            7
                    6          6
                     5        5
                      4      4
                       3    3
                        2  2
                         1
                  

                  看到其他答案后,我可以跳过一大堆循环。只是决定在最后完成它并尽快完成。

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2019-07-11
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多