Published at Nov 23 2018
·
0 comments

Instructions

Test suite

Solution

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
```

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

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

Install assignment dependencies:

```
$ npm install
```

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`

.

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

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

```
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;
```

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

Level up your programming skills with 3,373 exercises across 50 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments