سؤال

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

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.

هل كانت مفيدة؟

المحلول

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();
        }
    }
}

نصائح أخرى

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.

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top