Avatar of brunnock

brunnock's solution

to Pascal's Triangle in the JavaScript Track

Published at Nov 23 2018 · 0 comments
Instructions
Test suite
Solution

Note:

This exercise has changed since this solution was written.

Compute Pascal's triangle up to a given number of rows.

In Pascal's Triangle each number is computed by adding the numbers to the right and left of the current position in the previous row.

    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1
# ... etc

Setup

Go through the setup instructions for Javascript to install the necessary dependencies:

https://exercism.io/tracks/javascript/installation

Requirements

Install assignment dependencies:

$ npm install

Making the test suite pass

Execute the tests with:

$ npm test

In the test suites all tests but the first have been skipped.

Once you get a test passing, you can enable the next one by changing xtest to test.

Source

Pascal's Triangle at Wolfram Math World http://mathworld.wolfram.com/PascalsTriangle.html

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

pascals-triangle.spec.js

import Triangle from './pascals-triangle';

describe('Triangle', () => {
  test('with one row', () => {
    expect(new Triangle(1).rows).toEqual([[1]]);
  });

  xtest('with two rows', () => {
    expect(new Triangle(2).rows).toEqual([[1], [1, 1]]);
  });

  xtest('with three rows', () => {
    expect(new Triangle(3).rows).toEqual([[1], [1, 1], [1, 2, 1]]);
  });

  xtest('last row', () => {
    expect(new Triangle(4).lastRow).toEqual([1, 3, 3, 1]);
  });

  xtest('fifth row', () => {
    expect(new Triangle(5).lastRow).toEqual([1, 4, 6, 4, 1]);
  });

  xtest('twentieth row', () => {
    const twentieth = [
      1,
      19,
      171,
      969,
      3876,
      11628,
      27132,
      50388,
      75582,
      92378,
      92378,
      75582,
      50388,
      27132,
      11628,
      3876,
      969,
      171,
      19,
      1];
    expect(new Triangle(20).lastRow).toEqual(twentieth);
  });
});
class Triangle {
  constructor (numRows) {
    this.rows=[[1]];
    for (let x=1; x<numRows; x++) {
      let priorRow = this.rows[x-1];
      this.lastRow=[];
      for (let y=0; y<=priorRow.length; y++) {
	this.lastRow[y] = (priorRow[y] || 0) + (priorRow[y-1] || 0);
      }
      this.rows.push(this.lastRow);
    }
  }
}
module.exports = Triangle;

Community comments

Find this solution interesting? Ask the author a question to learn more.

brunnock's Reflection

This solution will fail new Triangle(1).lastRow, however.