我目前正在努力寻找帕斯卡三角形的行序列。我想输入行号并输出列表中直到该行的数字序列。例如,(Pascal 4)
会给出结果(1 1 1 1 2 1 1 3 3 1)
.
我正在尝试使用我发现的算法。这是算法本身:
Vc = Vc-1 * ((r - c)/c)
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."
这是我到目前为止的代码:
(define pascal n)
(cond((zero? n) '())
((positive? n) (* pascal (- n 1) (/ (- n c)c))))
我知道这几乎没什么,但我一直在努力尝试用 a 来确定该函数的范围let
or a lambda
合并列值。此外,我也一直在递归方面苦苦挣扎。我真的不知道如何建立基本案例以及如何进入下一步。基本上,我到处都迷路了。我知道这并没有显示太多,但任何朝着正确方向迈出的一步将不胜感激。
使用作为指导entry在维基百科中,这是算法的简单实现,用于计算给定行和列的帕斯卡三角形中的值,如链接中所述:
#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))
例如,以下命令将返回前四行值,请注意行和列都以零开头:
(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)
现在我们需要一个过程将所有值粘在一起,直到所需的行;这适用于球拍:
(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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)