如何在 R 中编写帕斯卡三角形?

发布于 2024-08-28 17:31:53 字数 149 浏览 6 评论 0原文

我正在阅读有关编程的内容,其中一个练习涉及在 R 中对帕斯卡三角形进行编程。我的第一个想法是制作一个列表,然后向其中添加内容,但这效果不太好。然后我想到从一个向量开始,最后用它制作一个列表。然后我想到制作一个矩阵,并在最后列出一个列表。

不确定以哪种方式来解决这个问题。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

誰認得朕 2024-09-04 17:31:53

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

如果我正在开发,我会将其存储在列表中我自己,因为这是处理可变长度行的最自然的数据结构。但在做出决定之前,您确实需要澄清用例。您打算在生成数据后对其进行分析吗?

编辑:

这是用更少的循环重写的 Rosetta 解决方案,并将结果存储为列表:

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

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))
}
清风挽心 2024-09-04 17:31:53

使用帕斯卡三角形的属性:

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

我认为这段代码非常快。

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.

风吹雨成花 2024-09-04 17:31:53

这是避免循环的解决方案(R 不太喜欢循环):

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

您可以将 1:10 替换为任何向量,甚至是不连续的向量:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文