我正在尝试实现递归函数来查找两组的笛卡尔积。我目前的代码如下:
(define (cartesian-product set-1 set-2)
(let (b (set 2))
(cond [(empty? set-1) '()]
[(empty? set-2) (cartesian-product (rest set-1) b)]
[else (append (list (list (first set-1) (first set-2))) (cartesian product set-1 (rest set-2)))]))))
然而,我的逻辑存在错误,我无法精确定位。任何帮助表示赞赏!
答案 0 :(得分:0)
两个循环而不是一个循环怎么样?
(define (cartesian-product set-1 set-2)
(define (cartesian-product-helper element set)
(if (empty? set)
set
(cons (list element (first set))
(cartesian-product-helper element (rest set)))))
(if (or (empty? set-1)
(empty? set-2))
empty
(cons (cartesian-product-helper (first set-1) set-2)
(cartesian-product (rest set-1) set-2))))
您在逻辑中发现了该问题,并尝试在set-2
中保存(set 2)
(您在b
中输入错误标记为Welcome to DrRacket, version 6.1.1 [3m].
Language: racket; memory limit: 128 MB.
> (cartesian-product '(1 2 3) '(x y z))
'(((1 x) (1 y) (1 z))
((2 x) (2 y) (2 z))
((3 x) (3 y) (3 z)))
> (cartesian-product '(1 2 3) '())
'()
> (cartesian-product '() '(x y z))
'()
),但此值将在每次递归时被覆盖呼叫。如果你改为调用辅助函数,它循环遍历一组中的所有元素以及另一组的第一个元素,那么你的问题就会消失。
(define (cartesian-product set-1 set-2)
(if (or (empty? set-1)
(empty? set-2))
empty
(for/list ([i set-1])
(for/list ([j set-2])
(list i j)))))
或者,类似于球拍的东西:
{{1}}