如何通過組合長列表中的任意兩個元素(例如4個元素)來生成序列列表?使用較長列表中的任意兩個元素創建列表DrRacket
例如,我想'(1 2)
,'(1 3)
,'(1 4)
,'(2 3)
,'(2 4)
,並且'(3 4)
基於'(1 2 3 4)
得到。
如何通過組合長列表中的任意兩個元素(例如4個元素)來生成序列列表?使用較長列表中的任意兩個元素創建列表DrRacket
例如,我想'(1 2)
,'(1 3)
,'(1 4)
,'(2 3)
,'(2 4)
,並且'(3 4)
基於'(1 2 3 4)
得到。
的問題問的組合給定列表的2級列表。它可以產生正大小的組合,更一般的程序方面來實現:
(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))
在這種情況下,解決方案需要組合,而不是輸入列表的排列。在相關答案中描述的情況完全相反 –
您是正確的。我總是把這些落後。讓我們看看我是否可以修復這個例子...或者你也歡迎:-) – Peter
我已經修復它,在我的答案;) –