Published at Jul 13 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
```

To run the tests, run the command `busted`

from within the exercise directory.

For more detailed information about the Lua track, including how to get help if you're having trouble, please visit the exercism.io Lua language page.

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.

```
local Triangle = require('pascals-triangle')
describe('pascals-triangle', function()
it('should generate a triangle with one row', function()
assert.same({ { 1 } }, Triangle(1).rows)
end)
it('should generate a triangle with two rows', function()
assert.same({ { 1 }, { 1, 1 } }, Triangle(2).rows)
end)
it('should generate a triangle with three rows', function()
assert.same({ { 1 }, { 1, 1 }, { 1, 2, 1 } }, Triangle(3).rows)
end)
it('should allow the last row to be accessed directly', function()
assert.same({ 1, 2, 1 }, Triangle(3).last_row)
end)
it('should generate the fourth row correctly', function()
assert.same({ 1, 3, 3, 1 }, Triangle(4).last_row)
end)
it('should generate the fifth row correctly', function()
assert.same({ 1, 4, 6, 4, 1 }, Triangle(5).last_row)
end)
it('should generate the twentieth row correctly', function()
local twentieth = { 1, 19, 171, 969, 3876, 11628, 27132, 50388, 75582, 92378, 92378, 75582, 50388, 27132, 11628, 3876, 969, 171, 19, 1 }
assert.same(twentieth, Triangle(20).last_row)
end)
end)
```

```
return function (nth)
local rows = {}
for i = 1, nth do
local elements = {1}
for j = 2, i do
elements[j] = rows[i-1][j-1] + (rows[i-1][j] or 0)
end
table.insert(rows,elements)
end
return {
rows = rows,
last_row = rows[nth]
}
end
```

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

- What compromises have been made?
- Are there new concepts here that you could read more about to improve your understanding?

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

## Community comments