7

I am reading about programming, and one exercise involved programming Pascal's triangle in R. My first idea was to make a list and then append things to it, but that didn't work too well. Then I thought of starting with a vector, and making a list out of that, at the end. Then I thought of making a matrix, and making a list out of that at the end.

Not sure which way to even approach this.

LinFelix
  • 1,026
  • 1
  • 13
  • 23
Peter Flom
  • 2,008
  • 4
  • 22
  • 35
  • The most convenient storing structure would probably depend on the algorithm that you want to use. After all, R does have a `choose` function. – Aniko Apr 13 '10 at 19:19

3 Answers3

10

There is one solution on Rosetta Code:

pascalTriangle <- function(h) {
  for(i in 0:(h-1)) {
    s <- ""
    for(k in 0:(h-i)) s <- paste(s, "  ", sep="")
    for(j in 0:i) {
      s <- paste(s, sprintf("%3d ", choose(i, j)), sep="")
    }
    print(s)
  }
}

I would store this in a list if I was developing it myself, since that is the most natural data structure to handle variable length rows. But you really would need to clarify a use case before making that decision. Are you intending on doing analysis on the data after it has been generated?

Edit:

Here is the Rosetta solution rewritten with less looping, and storing the results as a list:

pascalTriangle <- function(h) {
  lapply(0:h, function(i) choose(i, 0:i))
}
Shane
  • 98,550
  • 35
  • 224
  • 217
  • I always check Rosetta Code first for something as generic as that. Although the solutions usually aren't optimal, they can help as a first step. – Shane Apr 13 '10 at 19:31
  • `pascalTriangle <- function(h) { sapply(0:h, function(i) choose(0:h, i)) }` returns the triangle as a square matrix – Enrique Pérez Herrero Aug 29 '16 at 10:40
4

using a property of the Pascal triangle:

x <- 1
print(x)
for (i in 1:10) { x <- c(0, x) + c(x, 0); print(x) }

I suppose this code is very fast.

jogo
  • 12,469
  • 11
  • 37
  • 42
0

Here's a solution avoiding loops (R is not a big fan of loops):

sapply(1:10, function(n) sapply(0:n, function(k) choose(n, k)))

You can replace 1:10 with any vector, even noncontiguous ones:

R> sapply(c(5, 10), function(n) sapply(0:n, function(k) choose(n, k)))
[[1]]
[1]  1  5 10 10  5  1

[[2]]
[1]   1  10  45 120 210 252 210 120  45  10   1
Waldir Leoncio
  • 10,853
  • 19
  • 77
  • 107