如何在 R 中编写帕斯卡三角形?
我正在阅读有关编程的内容,其中一个练习涉及在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Rosetta Code 上有一个解决方案:
如果我正在开发,我会将其存储在列表中我自己,因为这是处理可变长度行的最自然的数据结构。但在做出决定之前,您确实需要澄清用例。您打算在生成数据后对其进行分析吗?
编辑:
这是用更少的循环重写的 Rosetta 解决方案,并将结果存储为列表:
There is one solution on Rosetta Code:
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:
使用帕斯卡三角形的属性:
我认为这段代码非常快。
using a property of the Pascal triangle:
I suppose this code is very fast.
这是避免循环的解决方案(R 不太喜欢循环):
您可以将
1:10
替换为任何向量,甚至是不连续的向量:Here's a solution avoiding loops (R is not a big fan of loops):
You can replace
1:10
with any vector, even noncontiguous ones: