Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

math - How would you program Pascal's triangle in R?

I am reading, on my own (not for HW) 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.

Any hints?

thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...