How would you program the Pascal triangle in R?

I read on my own (and not for HW) about programming, and one exercise involves programming the Pascal triangle in R. My first idea was to make a list and then add things to it, but that didn't work either. Well. Then I thought to start with a vector and make a list of it, at the end. Then I thought about creating a matrix and compiling a list from this at the end.

I don’t know which way to even approach this.

Any clues?

thank

+3
source share
2 answers

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)
  }
}

, , . , . ?

Edit:

Rosetta, :

pascalTriangle <- function(h) {
  lapply(0:h, function(i) choose(i, 0:i))
}
+8

:

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

, .

+1

Source: https://habr.com/ru/post/1740984/


All Articles