Pascal's triangle

From Rosetta Code
Revision as of 21:11, 23 June 2008 by rosettacode>Mwn3d (Created task with Java)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Pascal's triangle
You are encouraged to solve this task according to the task description, using any language you may know.

Pascal's triangle is an interesting math concept. Its first few rows look like this:

   1
  1 1
 1 2 1
1 3 3 1

where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row would be 1 (since the first element of each row doesn't have two elements above it), 4 (1 + 3), 6 (3 + 3), 4 (3 + 1), and 1 (since the last element of each row doesn't have two elements above it). Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.

Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for n <= 0 does not need to be uniform, but should be noted.

Java

Summing from Previous Rows

Works with: Java version 1.5+

This implementation prints nothing for n <= 0. <java>import java.util.LinkedList; ...//class definition, etc. public static void genPyrN(int rows){ if(rows <= 0) return; //save the last row here LinkedList<Integer> last= new LinkedList<Integer>(); last.add(1);//it's row 0...it starts with 1 for(int i= 0;i <= rows;++i){ //work on the next row LinkedList<Integer> thisRow= new LinkedList<Integer>(); for(int j= 0;j < i;++j){//loop the number of elements in this row if(j == last.size() || j == 0){//if we're on the ends thisRow.add(1); }else{//otherwise, sum from the last row thisRow.add(last.get(j - 1) + last.get(j)); } } thisRow.add(1); last= thisRow;//save this row System.out.println(thisRow); } }</java>