pascal triangle proper formatting java

て烟熏妆下的殇ゞ 提交于 2020-01-16 10:53:01

问题


so I'm currently working on an assignment that I just can't seem to finish. Well I have everything finished but would like the extra credit. I've been looking around the web and can't really seem to find exactly what I'm looking for.

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

}

}

The only issue that I'm having now is to properly format the output to look like an actual triangle. Any suggestions would be very helpful at this point in time. Thanks in advance


回答1:


One approach to this, is, assuming you have all numbers formatted to the same width, is to treat the problem as that of centering the lines.

Java Coding left as exercise to reader but essentially:

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



回答2:


Try to use the technique at http://www.kodejava.org/examples/16.html to make an array with array.length - i - 1 spaces (need to add the number spaces between numbers.. and 2 number of 2 digit numbers if any..).

Print this array at the start of the outer for loop.




回答3:


The challenge here is that you want to start printing at the top of the triangle, but you don't know where to center each row until you get to the last (and widest) row of the triangle. The trick is to not print anything until you know how wide the last row is. One way to do this is to generate all the rows as String (or StringBuilder) objects and compute the maximum width. Then, from the top, center each line by first printing an appropriate number of spaces. The correct number of spaces will be

(maxLineLength - currentLine.length()) / 2

Alternatively, you can simply assume a maximum line length and center all lines in that width. If the longer lines exceed the maximum width, then the triangle will be distorted below a certain row. (Just be sure to not try printing a negative number of spaces!)




回答4:


If anyone is looking for the actual code to do this take a look at my implementation in Java, it's similar to what Craig Taylor mentioned (numbers formatted to the same width) plus it uses an algorithm to compute the elements without memory (or factorials).

The code has comments explaining each step (calculation and printing):

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

Hope it helps someone!



来源:https://stackoverflow.com/questions/14371775/pascal-triangle-proper-formatting-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!