2013-08-05 47 views

回答

0

我想你想要所有的排列按照this answer

用他的排列函數的定義,你可以這樣做:

(permutations 2 '(1 2 3 4)) 
+0

在這種情況下,解決方案需要組合,而不是輸入列表的排列。在相關答案中描述的情況完全相反 –

+0

您是正確的。我總是把這些落後。讓我們看看我是否可以修復這個例子...或者你也歡迎:-) – Peter

+0

我已經修復它,在我的答案;) –

3

的問題問的組合給定列表的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)) 
+0

這是一個非常好的答案,但我很驚訝沒有發現它在球拍中,因爲它同時存在於Python(itertools)和Clojure(math.combinatorics) – Peter

+0

同意中。應該存在一個標準的球拍組合模塊,使用流 –

+0

你在想我在想什麼嗎? ;-) – Peter

2

這裏只是一個解決方案(一個功能,一個參數)。對於像'(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)) 
相關問題