帕斯卡的三角形行序列 [英] Pascal's Triangle Row Sequence
问题描述
我目前正在寻找Pascal三角形的行序列.我想输入行号并输出列表中的数字序列,直到该行为止.例如,(Pascal 4)
将给出结果(1 1 1 1 2 1 1 3 3 1)
.
I'm currently working on finding the row sequences of Pascal's triangle. I wanted to input the row number and output the sequence of numbers in a list up until that row. For example, (Pascal 4)
would give the result (1 1 1 1 2 1 1 3 3 1)
.
我正在尝试使用发现的算法.这是算法本身:
I am trying to use an algorithm that I found. Here is the algorithm itself:
V c = V c-1 *((r-c)/c)
Vc = Vc-1 * ((r - c)/c)
r 和 c 应该是行和列,并且V 0 = 1.该算法可以在维基百科页面上的计算和单个行或对角线"部分中找到.
r and c are supposed to be row and column, and V0=1. The algorithm can be specifically found on the wikipedia page in the section titled "Calculating and Individual Row or Diagonal."
这是我到目前为止的代码:
Here is the code that I have so far:
(define pascal n)
(cond((zero? n) '())
((positive? n) (* pascal (- n 1) (/ (- n c)c))))
我知道几乎没有什么,但是我一直在努力寻找用let
或lambda
合并函数字段值的作用域.另外,我也一直在努力递归.我真的不知道如何建立基本案例以及如何进行下一步.基本上,我到处都迷路了.我知道这并没有显示太多,但是朝着正确方向迈出的任何一步都将不胜感激.
I know that's hardly anything but I've been struggling a lot on trying to find scoping the function with a let
or a lambda
to incorporate column values. Additionally, I've also been struggling on the recursion. I don't really know how to establish the base case and how to get to the next step. Basically, I've been getting pretty lost everywhere. I know this isn't showing much, but any step in the right direction would be greatly appreciated.
推荐答案
使用 entry 在Wikipedia中,这是算法的直接实现,用于在给定Pascal Triangle中的行和列的情况下计算值,如链接中所述:
Using as a guide the entry in Wikipedia, this is a straightforward implementation of the algorithm for calculating a value in the Pascal Triangle given its row and column, as described in the link:
#lang racket
(define (pascal row column)
(define (aux r c)
(if (zero? c)
1
(* (/ (- r c) c)
(aux r (sub1 c)))))
(aux (add1 row) column))
例如,以下代码将返回值的前四行,注意行和列均以零开头:
For example, the following will return the first four rows of values, noticing that both rows and columns start with zero:
(pascal 0 0)
(pascal 1 0)
(pascal 1 1)
(pascal 2 0)
(pascal 2 1)
(pascal 2 2)
(pascal 3 0)
(pascal 3 1)
(pascal 3 2)
(pascal 3 3)
现在,我们需要一个过程将所有值粘贴在一起,直到所需的行;这适用于球拍:
Now we need a procedure to stick together all the values up until the desired row; this works for Racket:
(define (pascal-up-to-row n)
(for*/list ((i (in-range n))
(j (in-range (add1 i))))
(pascal i j)))
结果符合预期:
(pascal-up-to-row 4)
> '(1 1 1 1 2 1 1 3 3 1)
这篇关于帕斯卡的三角形行序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!