【问题标题】:pascal triangle proper formatting java帕斯卡三角形正确格式化java
【发布时间】:2013-01-17 03:27:25
【问题描述】:

所以我目前正在处理一项我似乎无法完成的任务。好吧,我已经完成了一切,但想要额外的功劳。我一直在网上四处寻找,但似乎无法找到我正在寻找的确切内容。

public class PascalTester
{
  public static void main(String[] args)
  {
    Scanner kb = new Scanner(System.in);

    System.out.println("Welcome to the Pascal's Triangle program!");
    System.out.println("Please enter the size of the triangle you want");

    int size = kb.nextInt();

    int[][] myArray = new int[size][size];

    myArray = fillArray(myArray); 

    //myArray = calculateArray(myArray);

    printArray(myArray); //prints the array

}

private static int[][] fillArray(int[][] array)
{
    array[0][1] = 1;

    for (int i = 1; i < array.length; i++)
    {
        for (int j = 1; j < array[i].length; j++)
        {
            array[i][j] = array[i-1][j-1] + array[i-1][j];
        }
    }

    return array;
}

private static void printArray(int[][] array)
{
    for (int i = 0; i < array.length; i++)
    {
        for (int j = 0; j < array[i].length; j++)
        {
            if(array[i][j] != 0)
            System.out.print(array[i][j] + " ");
        }
        System.out.println();
    }

}

}

我现在唯一遇到的问题是正确格式化输出,使其看起来像一个实际的三角形。此时任何建议都会非常有帮助。提前致谢

【问题讨论】:

  • 当前输出是多少?你希望它看起来像什么?你试过什么?
  • 这是一个直角三角形 atm,我正在寻找一个等腰三角形。我试过弄乱 printf 格式,但是当我这样做时,我在编译器中遇到错误
  • 你应该展示你尝试过的东西,毕竟,如果我们这样做了,你应该得到额外的荣誉吗?
  • 我一直在尝试不同的 printf 东西,看看我能不能把它变成标签和东西
  • 首先要做的是以你想要的格式手写出来,然后仔细考虑你到底做了什么。

标签: java formatting pascals-triangle


【解决方案1】:

解决此问题的一种方法是,假设您将所有数字格式化为相同的宽度,将问题视为使线条居中的问题。

Java 编码作为练习留给读者,但本质上是:

for lineText : triange lines 
   leadingSpacesCount = (80/2) - lineText.length(); 
   print " " x leadingSpacesCount + lineText

【讨论】:

    【解决方案2】:

    尝试使用http://www.kodejava.org/examples/16.html 的技术创建一个带有array.length - i - 1 空格的数组(需要在数字之间添加数字空格.. 和2 个数字,如果有的话..)。

    在外部 for 循环的开头打印此数组。

    【讨论】:

      【解决方案3】:

      这里的挑战是您想从三角形的顶部开始打印,但是在到达三角形的最后(也是最宽的)行之前,您不知道将每行居中的位置。诀窍是在您知道最后一行有多宽之前不打印任何内容。一种方法是将所有行生成为String(或StringBuilder)对象并计算最大宽度。然后,从顶部开始,通过首先打印适当数量的空格来使每行居中。正确的空格数为

      (maxLineLength - currentLine.length()) / 2
      

      或者,您可以简单地假设最大线条长度并将所有线条居中在该宽度中。如果较长的线超过最大宽度,则三角形将在某一行下方扭曲。 (请确保不要尝试打印负数的空格!)

      【讨论】:

        【解决方案4】:

        如果有人正在寻找执行此操作的实际代码,请查看我在 Java 中的实现,它类似于 Craig Taylor 提到的(格式化为相同宽度的数字)加上它使用一种算法来计算没有内存的元素(或阶乘)。

        代码有 cmets 解释每个步骤(计算和打印):

        /**
         * This method will print the first # levels of the Pascal's triangle. It
         * uses the method described in:
         * 
         * https://en.wikipedia.org/wiki/Pascal%27s_triangle#Calculating_a_row_or_diagonal_by_itself
         * 
         * It basically computes the Combinations of the current row and col
         * multiplied by the previous one (which will always be 1 at the beginning
         * of each pascal triangle row). It will print each tree element to the output
         * stream, aligning the numbers with spaces to form a perfect triangle.
         * 
         * @param num
         *            # of levels to print
         */
        public static void printPascalTriangle(int num) {
            // Create a pad (# of spaces) to display between numbers to keep things
            // in order. This should be bigger than the # of digits of the highest
            // expected number and it should be an odd number (to have the same
            // number of spaces to the left and to the right between numbers)
            int pad = 7;
        
            // Calculate the # of spaces to the left of each number plus itself
            // (this is the width of the steps of the triangle)
            int stepsWidth = pad / 2 + 1;
        
            // Now calculate the maximum # of spaces from the left side of the
            // screen to the first triangle's level (we will have num-1 steps in the
            // triangle)
            int spaces = (num - 1) * stepsWidth;
        
            for (int n = 0; n < num; n++) {
                // Print the left spaces of the current level, deduct the size of a
                // number in each row
                if (spaces > 0) {
                    System.out.printf("%" + spaces + "s", "");
                    spaces -= stepsWidth;
                }
                // This will represent the previous combination C(n k-1)
                int prevCombination = 1;
                for (int k = 1; k <= n + 1; k++) {
                    System.out.print(prevCombination);
        
                    // Calculate how many digits this number has and deduct that to
                    // the pad between numbers to keep everything aligned
                    int digits = (int) Math.log10(prevCombination);
                    if (digits < pad) {
                        System.out.printf("%" + (pad - digits) + "s", "");
                    }
        
                    // Formula from Wikipedia (we can remove that "+1" if we start
                    // the row loop at n=1)
                    prevCombination = prevCombination * (n + 1 - k) / k;
        
                }
                // Row separator
                System.out.println();
            }
        }
        

        希望它对某人有所帮助!

        【讨论】:

        • 即使链接可能包含答案,也请在此处发布您的相关代码。
        • 好电话。发布的是代码而不是链接。
        猜你喜欢
        • 2011-05-07
        • 1970-01-01
        • 1970-01-01
        • 2014-06-10
        • 1970-01-01
        • 1970-01-01
        • 2013-11-19
        • 2012-10-24
        • 1970-01-01
        相关资源
        最近更新 更多