【发布时间】:2013-08-06 13:53:03
【问题描述】:
如何通过组合较长列表中的任意两个元素(例如 4 个元素)来生成序列列表?
例如,我想根据'(1 2 3 4)得到'(1 2)、'(1 3)、'(1 4)、'(2 3)、'(2 4)和'(3 4)。
【问题讨论】:
标签: list scheme racket combinations elements
如何通过组合较长列表中的任意两个元素(例如 4 个元素)来生成序列列表?
例如,我想根据'(1 2 3 4)得到'(1 2)、'(1 3)、'(1 4)、'(2 3)、'(2 4)和'(3 4)。
【问题讨论】:
标签: list scheme racket combinations elements
问题要求提供给定列表的 组合 的 2 大小列表。它可以根据产生 n 大小组合的更一般的过程来实现:
(define (combinations size elements)
(cond [(zero? size)
'(())]
[(empty? elements)
empty]
[else
(append (map (curry cons (first elements))
(combinations (sub1 size) (rest elements)))
(combinations size (rest elements)))]))
当我们指定size=2时,它会按预期工作:
(combinations 2 '(1 2 3 4))
=> '((1 2) (1 3) (1 4) (2 3) (2 4) (3 4))
【讨论】:
这是您指定的解决方案(一个函数,一个参数)。对于像'(next rest ...) 这样的输入,解决方案会计算next 的结果,然后在rest ... 上递归 - 使用append 将这两个部分结合起来。
(define (combine elts)
(if (null? elts)
'()
(let ((next (car elts))
(rest (cdr elts)))
(append (map (lambda (other) (list next other)) rest)
(combine rest)))))
> (combine '(1 2 3 4))
((1 2) (1 3) (1 4) (2 3) (2 4) (3 4))
【讨论】:
【讨论】: