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
The rule that Pascal's triangle has is that we start with 1 at the top, then 1s at both sides of the triangle until the end. The middle numbers, each is the sum of the two consecutive numbers just above it. Hence to construct a Pascal's triangle we just need to add the two numbers just above the number.
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))
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With