Tuesday, November 14, 2017

Pascal Triangle In Java

Pascal Triangle is one of the most interesting number pattern which is a triangular array of the binomial coefficients. The following example shows how to generate this triangle in Java.





Analysis:

1. Very first number of the triangle is 1.
2. Every row except the first one starts and ends with 1.
3. Other each number of the subsequent row is calculated by adding the number above and to the left.
4. To calculation, maintain 2 arrays. One is for current row and other is for previous row.
5. Swap current row and previous row after each iteration.

Here's the implementation:

private void drawTriangle() {
 int currentIndex = 1;
 int previousIndex = 0;
 /* Print very first number of the triangle */
 System.out.println("1");
 for (int i = 2; i <= LIMIT; i++) {
  /* First number always 1 */
  record[currentIndex][1] = 1;
  
  /* Print first number of a row */
  System.out.print("1");
  
  for (int j = 2; j < i; j++) {
   /* Calculate current number adding previous row's two numbers */
   record[currentIndex][j] = record[previousIndex][j] + record[previousIndex][j - 1];
   System.out.print(" " + record[currentIndex][j]);
  }
  
  /* Save last number of the current row */
  record[currentIndex][i] = 1;
  
  /* Print last number of this row */
  System.out.println(" 1");

  /* Swap current index & previous index */
  currentIndex = currentIndex == 0 ? 1 : 0;
  previousIndex = previousIndex == 0 ? 1 : 0;
 }
}

Download full source code from here - Algorithm In Java
For any comment or improvement, Please drop a message in the comment section.

No comments:

Post a Comment