🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of katrinleinweber

katrinleinweber's solution

to Pascal's Triangle in the R Track

Published at Jul 13 2018 · 0 comments
Test suite

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

How to implement your solution

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.

How to run tests

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

Submitting Incomplete Solutions

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



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", {

test_that("null/no rows", {

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)
  else if (n == 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]

Community comments

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

What can you learn from this solution?

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?