Search code examples
javapascals-triangle

Pascal's triangle, calculating number at given row and column Java


I have a small assignment where I have to produce a pascal triangle and then find a number given a user inputted row and column. This is all I have come up with, I do not know how to proceed with calculating the number at a given row and column.

import java.util.Scanner;

public class PascalTriangle {

   public static void print(int n) {
       for (int i = 0; i < n; i++) {
           for (int j = 0; j <= i; j++) {
               System.out.print(pascal(i, j) + " ");
           }
           System.out.println();
       }
   }

   public static int pascal(int i, int j) {
       if (j == 0) {
           return 1;
       } else if (j == i) {
           return 1;
       } else {
           return pascal(i - 1, j - 1) + pascal(i - 1, j);
       }

   }

   public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
       System.out.print("Enter the row number");
       int row = scanner.nextInt();
       print(row);
   }
}

Solution

  • First, your code will be very slow. I'm not going to do your assignment, but you can compute the next line of Pascal's triangle by just knowing the previous one, in constant time for each cell, while you are currently using a huge time re-computing the same values.

    Second, for your actual question, you can check out the formula of a cell in the Pascal Triangle. It is not the right way to go, but can still be a starting point for documenting yourself on the Pascal triangle.

    Using this formula, you can compute the number at a given position by computing only its row.

    EDIT

    Your recent comment seems to point to a will not to compute the value at a position, but to compute the position of a value. Beforehand, there is absolutely no unicity of such a position: almost all values appear at least twice in the triangle, for it is symmetrical.

    But if you want to return e.g. the first in lexicographical order of those positions, you could just compute the rows one by one (using the same scheme as to display the triangle) and then stop as soon as you get the wanted value.