Main Content

Binomial Coefficient (Pascal Triangle) objects in Java

Archive - Originally posted on "The Horse's Mouth" - 2015-02-03 20:38:46 - Graham Ellis

An exercise on our Java course from which our delegates gain a lot of appreciation is the one in which I ask them to set up an array of arrays containing Pascal's Triangle of Binomial Coefficients. It sounds mighty complex, but I explain it on the board and it comes down to just defining the arrays and filling the elements with simple additions.

Arrays and Objects are both fundamental to Java, and our course teaches both; and until delegates know about both (and about other things too!) they can't really write fully mature Java programs - and neither can I while I'm teaching. Arrays are usually covered first, so the sample answers you'll previously have found on our web site are in-line coded (perhaps with some calls to static methods) which - if I were interviewing for a job - would have me asking "Did you consider using a class of objects"?

Today, I taught objects before I taught arrays - I felt it was right to swap them around for the group I have , and it worked well. It also enabled me to use an object like I really should for my Pascal's Triangle.

Here's my main code - make a triangle of 10 rows, print it out, look up an element:

  public static void main (String [] args) {
    PascalAsObject pt = new PascalAsObject(10);
    pt.prettyPrint();
    System.out.println(pt.getRowCol(6,3));
  }


The beauty is that the control code is so straight forward, the detail of the triangle isn't exposed to the top level and (importantly) the methods in the PascalAsObject class are available for use in other programs, without the user needing to have any knowledge of how they work.

How does that work?

  WomanWithCat:dvla_4 grahamellis$ java PascalAsObject
                                   1
                                1     1
                             1     2     1
                          1     3     3     1
                       1     4     6     4     1
                    1     5    10    10     5     1
                 1     6    15    20    15     6     1
              1     7    21    35    35    21     7     1
           1     8    28    56    70    56    28     8     1
        1     9    36    84   126   126    84    36     9     1


Full source code [here].