帕斯卡三角形二维数组 - 格式化打印输出

发布于 2024-12-27 18:04:43 字数 1275 浏览 0 评论 0原文

我有一个小作业,必须使用二维数组来生成帕斯卡三角形。这是我的代码,它有效。如果我像这样显示三角形,则有额外的机会:

帕斯卡三角形
(来源:daugerresearch.com

但是,我的间距不是像这样格式化。它只是显示所有在左侧排列的数字。它很难描述,但如果你运行它,你就会明白我的意思。

这是我的代码:

public class Pascal {
    public static final int ROW = 16;
    public static void main(String[] args) {
        int[][] pascal = new int[ROW + 1][];
        pascal[1] = new int[1 + 2];
        pascal[1][1] = 1;
        for (int i = 2; i <= ROW; i++) {
            pascal[i] = new int[i + 2];
            for (int j = 1; j < pascal[i].length - 1; j++) {
                pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j];
            }
        }
        for (int i = 1; i <= ROW; i++) {
            for (int j = 1; j < pascal[i].length - 1; j++) {
                System.out.print(pascal[i][j] + " ");
            }
            System.out.println();
        }
    }
}

如果有人可以帮助我弄清楚如何向我的程序添加正确的间距以产生图片中所需的输出,那就太好了。我知道我需要在某个地方放置一个 System.out.print(" ") 。我只是不知道在哪里。

I have a small assignment where I have to use a 2d array to produce Pascal's triangle. Here is my code, and it works. There is an extra credit opportunity if I display the triangle like so:

Pascal's triangle
(source: daugerresearch.com)

However, my spacing is not formatted like that. it simply displays the numbers all lined up on the left. its hard to describe but if you run it you will see what I mean.

Here is my code:

public class Pascal {
    public static final int ROW = 16;
    public static void main(String[] args) {
        int[][] pascal = new int[ROW + 1][];
        pascal[1] = new int[1 + 2];
        pascal[1][1] = 1;
        for (int i = 2; i <= ROW; i++) {
            pascal[i] = new int[i + 2];
            for (int j = 1; j < pascal[i].length - 1; j++) {
                pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j];
            }
        }
        for (int i = 1; i <= ROW; i++) {
            for (int j = 1; j < pascal[i].length - 1; j++) {
                System.out.print(pascal[i][j] + " ");
            }
            System.out.println();
        }
    }
}

If someone could help me figure out how to add the correct spacing to my program to produce the output desired in the picture, that would be great. I know I need to put a System.out.print(" ") somewhere. I just dont know where.

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

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

发布评论

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

评论(5

南街女流氓 2025-01-03 18:04:43

在这里,我修改了您的代码,由于我的控制台窗口的限制,它对于 ROW 大小到 13 的打印效果非常好:

import java.util.*;

public class Pascal {
    public static final int ROW = 12;
    private static int max = 0;

    public static void main(String[] args) {
        int[][] pascal = new int[ROW + 1][];
        pascal[1] = new int[1 + 2];
        pascal[1][1] = 1;
        for (int i = 2; i <= ROW; i++) {
            pascal[i] = new int[i + 2];
            for (int j = 1; j < pascal[i].length - 1; j++) {
                pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j];
                String str = Integer.toString(pascal[i][j]);
                int len = str.length();
                if (len > max)
                    max = len;
            }
        }

        for (int i = 1; i <= ROW; i++) {
            for (int k = ROW; k > i; k--)
                System.out.format("%-" + max + "s", " ");
            for (int j = 1; j < pascal[i].length - 1; j++)
                System.out.format("%-" + (max + max) + "s", pascal[i][j]);
            System.out.println();
        }
    }
}

输出:

                                 1     
                              1     1     
                           1     2     1     
                        1     3     3     1     
                     1     4     6     4     1     
                  1     5     10    10    5     1     
               1     6     15    20    15    6     1     
            1     7     21    35    35    21    7     1     
         1     8     28    56    70    56    28    8     1     
      1     9     36    84    126   126   84    36    9     1     
   1     10    45    120   210   252   210   120   45    10    1     
1     11    55    165   330   462   462   330   165   55    11    1     

Here I had modified your code, it prints wonderfully for ROW size till 13, because of the limitation of my console window:

import java.util.*;

public class Pascal {
    public static final int ROW = 12;
    private static int max = 0;

    public static void main(String[] args) {
        int[][] pascal = new int[ROW + 1][];
        pascal[1] = new int[1 + 2];
        pascal[1][1] = 1;
        for (int i = 2; i <= ROW; i++) {
            pascal[i] = new int[i + 2];
            for (int j = 1; j < pascal[i].length - 1; j++) {
                pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j];
                String str = Integer.toString(pascal[i][j]);
                int len = str.length();
                if (len > max)
                    max = len;
            }
        }

        for (int i = 1; i <= ROW; i++) {
            for (int k = ROW; k > i; k--)
                System.out.format("%-" + max + "s", " ");
            for (int j = 1; j < pascal[i].length - 1; j++)
                System.out.format("%-" + (max + max) + "s", pascal[i][j]);
            System.out.println();
        }
    }
}

Output:

                                 1     
                              1     1     
                           1     2     1     
                        1     3     3     1     
                     1     4     6     4     1     
                  1     5     10    10    5     1     
               1     6     15    20    15    6     1     
            1     7     21    35    35    21    7     1     
         1     8     28    56    70    56    28    8     1     
      1     9     36    84    126   126   84    36    9     1     
   1     10    45    120   210   252   210   120   45    10    1     
1     11    55    165   330   462   462   330   165   55    11    1     
要走就滚别墨迹 2025-01-03 18:04:43

您遇到间距问题,因为您需要向某些数字添加空格以容纳较大数字占用的空间。首先确定您计划打印的最大数字是多少(以编程方式)。然后确定该数字 log(n) 中的位数。然后,您可以使用此数字为位数少于最大数字的数字打印空白,以使打印看起来更好。

You're encountering spacing issues because you need to add whitespace to certain numbers to accommodate space that larger numbers occupy. First determine what the largest number you plan to print is (programmatically). Then determine the number of digits in that number log(n). You can then use this number to print whitespace for numbers that have less digits than your largest number to make your printing look nicer.

撞了怀 2025-01-03 18:04:43

您可以在二维数组的左上角构建一个帕斯卡三角形,如下所示:

 1  1  1  1  1  1  1  1  1  1
 1  2  3  4  5  6  7  8  9
 1  3  6 10 15 21 28 36
 1  4 10 20 35 56 84
 1  5 15 35 70 126
 1  6 21 56 126
 1  7 28 84
 1  8 36
 1  9
 1

两个嵌套:在行上,然后在列上。第一行和第一列的元素都等于1,所有其他元素都是该行和列中前一个元素的总和。

int n = 10;
// an array of 'n' rows
int[][] arr = new int[n][];
// iterate over the rows of the array
IntStream.range(0, n)
        // a row of 'n-i' elements
        .peek(i -> arr[i] = new int[n - i])
        // iterate over the elements of the row
        .forEach(i -> IntStream.range(0, n - i).forEach(j -> {
            if (i == 0 || j == 0)
                // elements of the first row
                // and column are equal to one
                arr[i][j] = 1;
            else
                // all other elements are the sum of the
                // previous element in the row and column
                arr[i][j] = arr[i][j - 1] + arr[i - 1][j];
        }));
// formatted output
Arrays.stream(arr)
        .map(row -> Arrays.stream(row)
                // format as a two-digit number
                .mapToObj(i -> String.format("%2d", i))
                .collect(Collectors.joining(" ")))
        .forEach(System.out::println);

时,格式为两位数

"%2d" - 当 n=10"%4d" - 当n=16时,格式为四位数字,依此类推。

You can build a Pascal's triangle in the upper left corner of a 2d array that looks like this:

 1  1  1  1  1  1  1  1  1  1
 1  2  3  4  5  6  7  8  9
 1  3  6 10 15 21 28 36
 1  4 10 20 35 56 84
 1  5 15 35 70 126
 1  6 21 56 126
 1  7 28 84
 1  8 36
 1  9
 1

Two nested streams: over the rows and then over the columns. Elements of the first row and column are equal to one, all other elements are the sum of the previous element in the row and column.

int n = 10;
// an array of 'n' rows
int[][] arr = new int[n][];
// iterate over the rows of the array
IntStream.range(0, n)
        // a row of 'n-i' elements
        .peek(i -> arr[i] = new int[n - i])
        // iterate over the elements of the row
        .forEach(i -> IntStream.range(0, n - i).forEach(j -> {
            if (i == 0 || j == 0)
                // elements of the first row
                // and column are equal to one
                arr[i][j] = 1;
            else
                // all other elements are the sum of the
                // previous element in the row and column
                arr[i][j] = arr[i][j - 1] + arr[i - 1][j];
        }));
// formatted output
Arrays.stream(arr)
        .map(row -> Arrays.stream(row)
                // format as a two-digit number
                .mapToObj(i -> String.format("%2d", i))
                .collect(Collectors.joining(" ")))
        .forEach(System.out::println);

"%2d" - format as a two-digit number, when n=10,

"%4d" - format as a four-digit number, when n=16, and so on.

江南烟雨〆相思醉 2025-01-03 18:04:43

您也可以参考下面的代码。

public class Pascal {
    public static final int ROW = 16;

    static long factorial(int ROW) {
        long f;
        for (f = 1; ROW > 1; ROW--) {
            f *= ROW;
        }
        return f;
    }

    static long patt(int ROW, int r) {
        return factorial(ROW) / (factorial(ROW - r) * factorial(r));
    }

    public static void main(String args[]) {
        System.out.println();
        int i, j;
        for (i = 0; i <= ROW; i++) {
            for (j = 0; j <= ROW - i; j++) {
                System.out.print(" ");
            }
            for (j = 0; j <= i; j++) {
                System.out.print(" " + patt(i, j));
            }
            System.out.println();
        }
    }
}

输出:

                  1
                 1 1
                1 2 1
               1 3 3 1
              1 4 6 4 1
             1 5 10 10 5 1
            1 6 15 20 15 6 1
           1 7 21 35 35 21 7 1
          1 8 28 56 70 56 28 8 1
         1 9 36 84 126 126 84 36 9 1
        1 10 45 120 210 252 210 120 45 10 1
       1 11 55 165 330 462 462 330 165 55 11 1
      1 12 66 220 495 792 924 792 495 220 66 12 1
     1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
    1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1
   1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
  1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1

You can also refer to the below code.

public class Pascal {
    public static final int ROW = 16;

    static long factorial(int ROW) {
        long f;
        for (f = 1; ROW > 1; ROW--) {
            f *= ROW;
        }
        return f;
    }

    static long patt(int ROW, int r) {
        return factorial(ROW) / (factorial(ROW - r) * factorial(r));
    }

    public static void main(String args[]) {
        System.out.println();
        int i, j;
        for (i = 0; i <= ROW; i++) {
            for (j = 0; j <= ROW - i; j++) {
                System.out.print(" ");
            }
            for (j = 0; j <= i; j++) {
                System.out.print(" " + patt(i, j));
            }
            System.out.println();
        }
    }
}

Output:

                  1
                 1 1
                1 2 1
               1 3 3 1
              1 4 6 4 1
             1 5 10 10 5 1
            1 6 15 20 15 6 1
           1 7 21 35 35 21 7 1
          1 8 28 56 70 56 28 8 1
         1 9 36 84 126 126 84 36 9 1
        1 10 45 120 210 252 210 120 45 10 1
       1 11 55 165 330 462 462 330 165 55 11 1
      1 12 66 220 495 792 924 792 495 220 66 12 1
     1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
    1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1
   1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
  1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1
野の 2025-01-03 18:04:43

关于这个上一个答案,您可以使用两个嵌套的增强型在左上角输出一个格式化的三角形循环。

    1    1    1    1    1    1    1    1    1    1    1    1    1    1
    1    2    3    4    5    6    7    8    9   10   11   12   13
    1    3    6   10   15   21   28   36   45   55   66   78
    1    4   10   20   35   56   84  120  165  220  286
    1    5   15   35   70  126  210  330  495  715
    1    6   21   56  126  252  462  792 1287
    1    7   28   84  210  462  924 1716
    1    8   36  120  330  792 1716
    1    9   45  165  495 1287
    1   10   55  220  715
    1   11   66  286
    1   12   78
    1   13
    1

<一href="https://tio.run/##hZPBbuIwEIbvPMWoUgWI0i5ST2X7CHvqEXEwxIHJJnbWHoOqLc/O/k 4Im5Cg5uKxMzP@5p9xpg5qbkttsuT3@VyGTc5b2ubKe/ql2NDfEEG7nHtRguVgOaECfycf4tjsVmtS buenF@f4sREy9E6L1@X17OWFlIGnU59kUxqbMTl79O2Y1brK5RBp9LE6MTjq5GDRTokme9COZK@rJD FhtKvsV@/UOppEFEbCH0ssP8lgmc3arA1bTFSDzXlMOteFNuI7bki/4nWbjubELb57jE22hhNXdWKup FlNmkXSmBtmn7ZSK0UAvcObvr5iGKwhvwvRLUDKzksPo9OqhLY2D0VsGQr4E1ROYskaPRhSS7PKojq LZc/lBAKv7/OpPCcLMPefNF4bUX0oLtT3gkunD2yDb2LRmkblVh3fYjc2dF@saVbvqw3@D5Q0Gt6d2t OKxhZKRCdkg5RBerOJgY@Yb/G22/615vctek1HA8XXN5CCYLCDmye8Y7y@UGyg5pFlP9izqHmSsLA1 aOxxj5H1pdriCUml3Ubv2Bi87l7kx6cXXTyjnucSz1/SyQM9viYPT8TTrkq3nrmZtDxqnU6j0/n8Dw" rel="nofollow noreferrer" title="Java (OpenJDK 8) – 在线试用">在线试用!

int n = 14;
// an array of 'n' rows
int[][] arr = new int[n][];
// iterate over the rows of the array
for (int i = 0; i < n; i++) {
    // a row of 'n-i' elements
    arr[i] = new int[n - i];
    // iterate over the elements of the row
    for (int j = 0; j < n - i; j++) {
        if (i == 0 || j == 0) {
            // elements of the first row
            // and column are equal to one
            arr[i][j] = 1;
        } else {
            // all other elements are the sum of the
            // previous element in the row and column
            arr[i][j] = arr[i][j - 1] + arr[i - 1][j];
        }
    }
}
// formatted output
for (int[] row : arr) {
    for (int i : row)
        // format as a four-digit number with one
        // additional whitespace at the beginning
        System.out.printf(" %4d", i);
    System.out.println();
}

With respect to this previous answer, you can output a formatted triangle in the upper left corner using two nested enhanced for loops.

    1    1    1    1    1    1    1    1    1    1    1    1    1    1
    1    2    3    4    5    6    7    8    9   10   11   12   13
    1    3    6   10   15   21   28   36   45   55   66   78
    1    4   10   20   35   56   84  120  165  220  286
    1    5   15   35   70  126  210  330  495  715
    1    6   21   56  126  252  462  792 1287
    1    7   28   84  210  462  924 1716
    1    8   36  120  330  792 1716
    1    9   45  165  495 1287
    1   10   55  220  715
    1   11   66  286
    1   12   78
    1   13
    1

Try it online!

int n = 14;
// an array of 'n' rows
int[][] arr = new int[n][];
// iterate over the rows of the array
for (int i = 0; i < n; i++) {
    // a row of 'n-i' elements
    arr[i] = new int[n - i];
    // iterate over the elements of the row
    for (int j = 0; j < n - i; j++) {
        if (i == 0 || j == 0) {
            // elements of the first row
            // and column are equal to one
            arr[i][j] = 1;
        } else {
            // all other elements are the sum of the
            // previous element in the row and column
            arr[i][j] = arr[i][j - 1] + arr[i - 1][j];
        }
    }
}
// formatted output
for (int[] row : arr) {
    for (int i : row)
        // format as a four-digit number with one
        // additional whitespace at the beginning
        System.out.printf(" %4d", i);
    System.out.println();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文