ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

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

See this guide for instructions on how to setup your local R environment.

In each problem folder, there is a file named `<exercise_name>.R`

containing a function that returns a `NULL`

value. Place your implementation inside the body of the function.

Inside of RStudio, simply execute the `test_<exercise_name>.R`

script. This can be conveniently done with testthat's `auto_test`

function. Because exercism code and tests are in the same folder, use this same path for both `code_path`

and `test_path`

parameters. On the command-line, you can also run `Rscript test_<exercise_name>.R`

.

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.

```
source("./pascals-triangle.R")
library(testthat)
context("pascals triangle")
test_that("zero rows", {
expect_equal(pascals_triangle(0), list())
})
test_that("single row", {
expect_equal(pascals_triangle(1), list(1))
})
test_that("two rows", {
expect_equal(pascals_triangle(2), list(1, c(1, 1)))
})
test_that("three rows", {
expect_equal(pascals_triangle(3), list(1, c(1, 1), c(1, 2, 1)))
})
test_that("four rows", {
expect_equal(pascals_triangle(4), list(1, c(1, 1), c(1, 2, 1), c(1, 3, 3, 1)))
})
test_that("negative rows", {
expect_error(pascals_triangle(-1))
})
test_that("null/no rows", {
expect_error(pascals_triangle(NULL))
})
message("All tests passed for exercise: pascals-triangle")
```

```
pascals_triangle <- function(n) {
# catch invalid input & edge cases
if (n < 0 | is.null(n))
stop("Invalid! Please provide n > 0!")
else if (n == 0)
list()
else if (n == 1)
list(1)
else if (n == 2)
list(1, c(1, 1))
else if (n >= 3) {
# construct triangle
t <- list(1, c(1, 1))
for (i in seq(3, n)) {
t <- append(t, list(c(i)))
t[[i]][1] <- 1
t[[i]][i] <- 1
# construct row
for (j in seq(2, i-1))
t[[i]][j] <- t[[i-1]][j-1] + t[[i-1]][j]
}
return(t)
}
}
```

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,450 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments